在 Python 的列表中移动对象时出现问题

Issue when moving an object inside a list in Python

这只是我的代码的一小部分(我是 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。

turtles[1]turtles[0] 是同一个对象。换句话说,turtles[1] is turtles[0].

要复制一个Turtle,使用.clone(),例如这里:

turtles[i] = turtles[i-1].clone()

虽然@wjandrea 的方法会奏效,但我认为这是错误的做法。海龟,除非重置屏幕或退出海龟,否则实际上是全局的。为每一个动作克隆它们中的每一个将创造出许多闲逛的海龟。相反,我会修正你的 list 逻辑:

from turtle import Turtle

turtles = []

for i in range(4):
    turtle = Turtle()
    turtle.setx(i * -20)

    turtles.append(turtle)

print("Before modification of element in position 0")
for i, turtle in enumerate(turtles):
    print(f"turtles[{i}] has xcor = {turtle.xcor()} [{id(turtle)}]")

# Move list forward

turtle = turtles.pop()
turtle.setx(turtles[0].xcor() + 20)
turtles.insert(0, turtle)

print("\nAfter modification of element in position 0")
for i, turtle in enumerate(turtles):
    print(f"turtles[{i}] has xcor = {turtle.xcor()} [{id(turtle)}]")

输出

> python3 test.py
Before modification of element in position 0
turtles[0] has xcor = 0 [4543646496]
turtles[1] has xcor = -20 [4557792880]
turtles[2] has xcor = -40 [4557793840]
turtles[3] has xcor = -60 [4557795280]

After modification of element in position 0
turtles[0] has xcor = 20 [4557795280]
turtles[1] has xcor = 0 [4543646496]
turtles[2] has xcor = -20 [4557792880]
turtles[3] has xcor = -40 [4557793840]
>