這只是我代碼的一小部分(我是 Python 新手)。目標是將所有元素向前移動一個位置。
from turtle import Turtle
turtles = []
for i in range(4):
t = Turtle()
t.color("white")
t.setx(i*-20)
turtles.append(t)
for i in range(len(turtles)-1, 0, -1):
print(f"Element in position {i} with xcor {turtles[i].xcor()} will have the xcor {turtles[i-1].xcor()}")
turtles[i] = turtles[i-1]
turtles[0].forward(20)
print(" After modification of element in position 0")
print(f"Element in position 0 has xcor = {turtles[0].xcor()}")
print(f"Element in position 1 has xcor = {turtles[1].xcor()}")
但是,我不明白為什么同時修改了位置 0 和 1 中的物件。
Element in position 3 with xcor -60 will have the xcor -40
Element in position 2 with xcor -40 will have the xcor -20
Element in position 1 with xcor -20 will have the xcor 0
After modification of element in position 0
Element in position 0 has xcor = 20.0
Element in position 1 has xcor = 20.0
我正在等待查看位置 1 中元素的 xcor = 0。
uj5u.com熱心網友回復:
turtles[1]并且turtles[0]是同一個物件。換句話說,turtles[1] is turtles[0]。
要復制Turtle,使用.clone(),例如,在這里:
turtles[i] = turtles[i-1].clone()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/357905.html
