【发布时间】:2021-11-16 04:55:30
【问题描述】:
这只是我代码的一小部分(我是 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] is turtles[0]。你为什么希望他们独立? -
用您自己的话说,当您执行
turtles[i] = turtles[i-1]循环时,您希望列表会发生什么?特别是,您期望turtles[0]是什么?你期望turtles[1]是什么?您是否希望它们是相同的Turtle,或者仅仅是分开的Turtles,它们是相同的或以某种方式复制的?您是否认为turtles[i] = turtles[i-1]创建了副本?它没有。 -
您可能想阅读 Ned Batchelder 的 Facts and myths about Python names and values,尤其是 this part:“事实:赋值从不复制数据”。尽管在您的情况下,您不是分配给名称,而是分配给列表的一个元素。
-
stackoverflow.com/questions/29191405/… 有帮助吗?我可以指出许多其他以前的问题,但似乎没有一个相当是正确的重复。
-
好的,感谢您的重播。我认为循环是在将对象移动到新位置之前创建对象的副本。但是现在有了你在一切都清楚之前提供的链接。
标签: python list python-turtle