这是我代码的一部分。当我执行程序时,我得到的输出包含在代码下面。你知道吗
currentPos = playerPosition
modifiedCords = freespaceCords
pathList = []
while(True):
adjacentList = []
potentialMoveList = []
currentPos[0] = currentPos[0] - 1
adjacentList.append(currentPos)
print(currentPos)
currentPos[0] = currentPos[0] + 2
adjacentList.append(currentPos)
print(currentPos)
currentPos[0] = currentPos[0] - 1
currentPos[1] = currentPos[1] - 1
adjacentList.append(currentPos)
print(currentPos)
currentPos[1] = currentPos[1] + 2
adjacentList.append(currentPos)
print(currentPos)
currentPos[1] = currentPos[1] - 1
print("")
print(adjacentList)
print("")
输出:
[0, 1]
[2, 1]
[1, 0]
[1, 2]
[[1, 1], [1, 1], [1, 1], [1, 1]]
我希望4个元素的列表包含前面四个单独打印的元素,以便:
[ [0,1] , [2,1] , [1,0] , [1,2] ]
请有人能提供一个解决我的问题,解释为什么他们的解决方案工作,为什么我的代码没有。你知道吗
谢谢你。你知道吗
您添加的引用不是列表的副本。 为了说明我们可以使用内置的
id
函数将以下代码添加到循环的末尾
您将发现
adjacentList
和currentPos
中的四个元素具有相同的id,这与内存中的对象完全相同。你知道吗不必使用许多方法中的一种附加
currentPos
的副本而不是引用(我只会提到一种方法,其他方法可以检查here)当你这么做的时候
您将引用附加到列表
currentPos
到adjacentList
。因此,每次更改currentPos
时,实际上也是在更改adjacentList
中的元素。如果您在中间步骤中打印adjacentList
,您就会明白我的意思。你知道吗为了避免这种情况,您可以附加列表的副本:
下面是一个示例,您可以看到我所描述的内容:
当您将
.append(currentPosition)
添加到列表中时,您将添加相同的实际对象4次。因为这个物体有4个位置,如果你改变它,所有的位置都会改变。最简单的方法是存储对象的副本,只需添加.append(list(currentPosition))
或.append(currentPosition[:])
即可。你知道吗相关问题 更多 >
编程相关推荐