元素的值与附加到lis的值不同

2024-09-30 01:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我代码的一部分。当我执行程序时,我得到的输出包含在代码下面。你知道吗

    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] ]

请有人能提供一个解决我的问题,解释为什么他们的解决方案工作,为什么我的代码没有。你知道吗

谢谢你。你知道吗


Tags: 代码true元素列表printappendwhile执行程序
3条回答

您添加的引用不是列表的副本。 为了说明我们可以使用内置的id函数

将以下代码添加到循环的末尾

print(id(adjacentList[0])
print(id(adjacentList[1])
print(id(adjacentList[2])
print(id(adjacentList[3])
print(id(currentPos))

您将发现adjacentListcurrentPos中的四个元素具有相同的id,这与内存中的对象完全相同。你知道吗

不必使用许多方法中的一种附加currentPos的副本而不是引用(我只会提到一种方法,其他方法可以检查here

# Since Python 3.3
adjacentList.append(currentPos.copy())

当你这么做的时候

adjacentList.append(currentPos)

您将引用附加到列表currentPosadjacentList。因此,每次更改currentPos时,实际上也是在更改adjacentList中的元素。如果您在中间步骤中打印adjacentList,您就会明白我的意思。你知道吗

为了避免这种情况,您可以附加列表的副本:

adjacentList.append(list(currentPos))

下面是一个示例,您可以看到我所描述的内容:

>>> l = [1, 1]
>>> adjacentList = []
>>> adjacentList.append(l)
>>> adjacentList
[[1, 1]]
>>> l[1] = 2
>>> adjacentList
[[1, 2]]

当您将.append(currentPosition)添加到列表中时,您将添加相同的实际对象4次。因为这个物体有4个位置,如果你改变它,所有的位置都会改变。最简单的方法是存储对象的副本,只需添加.append(list(currentPosition)).append(currentPosition[:])即可。你知道吗

相关问题 更多 >

    热门问题