首页 > 解决方案 > 尝试将列表附加到另一个列表时,所有元素都会发生变化,即使我使用“listB.append(listA[:]”进行附加来创建副本

问题描述

我正在尝试创建字段状态和移动列表。我通过附加当前字段状态来做到这一点,然后移动到一个列表中。但是,当我更改“字段”变量并再次附加它时,它会将列表中的所有元素更改为最新的。

我知道我正在附加一个参考,但是当我附加 'field[:]' 时它仍然不起作用,这应该创建一个副本。

抱歉,代码格式不正确,但在我的笔记本电脑上无法正常工作,已在我的原始代码中进行了格式化

data =  []

for i in range(0,1):
field = [[0, 0, 0],
         [0, 0, 0],
         [0, 0, 0]]

play = True

while play:
    compPlayed = False
    comp2Played = False

    # Loop until legal move made, which is when chosen field space = 0
    while comp2Played  == False:
        compRow2 = random.randint(0, 2)
        compCol2 = random.randint(0, 2)

        if field[compRow2][compCol2] == 0:

            # Create array containing the current field, and the legal move to be made
            gameArray = ([field,[compRow2,compCol2]])

            # Append copy to data list
            data.append(gameArray[:])
            print(data)

            # Update field and end loop
            field[compRow2][compCol2] = 1
            comp2Played = True

我希望“数据”列表包含每个字段状态和移动,但每次附加时,字段值都会更改为最新的,但移动保持不变。

>>[[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [2, 0]]] 

>>[[[[2, 0, 0], [0, 0, 0], [1, 0, 0]], [2, 0]], [[[2, 0, 0], 
  [0, 0,  0], [1, 0, 0]], [0, 2]]] 

这是我输出的一个例子。从第一次打印和第二次打印开始,字段值会发生变化。

标签: python-3.xlistreference

解决方案


推荐阅读