Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 复制一份清单_Python - Fatal编程技术网

Python 复制一份清单

Python 复制一份清单,python,Python,我试图制作一个“目标”,一个“网格”的副本。我不明白为什么这个代码不起作用 grid = [[randint(0, 1), randint(0, 1), randint(0, 1)], [randint(0, 1), randint(0, 1), randint(0, 1)], [randint(0, 1), randint(0, 1), randint(0, 1)]] target = [[0, 0, 0]] * 3 for x in range(3):

我试图制作一个“目标”,一个“网格”的副本。我不明白为什么这个代码不起作用

grid = [[randint(0, 1), randint(0, 1), randint(0, 1)],
        [randint(0, 1), randint(0, 1), randint(0, 1)],
        [randint(0, 1), randint(0, 1), randint(0, 1)]]

target = [[0, 0, 0]] * 3
for x in range(3):
    for y in range(3):
        target[x][y] = grid[x][y]

print target
print grid
结果如下:

[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[1, 0, 0], [0, 1, 1], [0, 1, 0]]
本部分:

target = [[0, 0, 0]] * 3
创建一个重复3次相同列表的列表。因此,对一个项目的更改实际上反映在所有项目中(它们是相同的对象)。您需要创建一个列表三次:

target = [[0, 0, 0] for _ in range(3)]
您应该只对对象(如果有的话)使用列表上的星号操作符(或列表乘法),因为您无法更改它们的状态,所以这些对象没有这个问题

不要忘记您可以使用(
x[:]
用于创建名为
x
的列表的浅副本,就像
list(x)
):

或者更一般地说:


哇!对于像我这样的新手来说,这是一件非常微妙的事情。谢谢@如果您可能不熟悉
x[:]
语法,那么这只是创建列表副本的一种方法——谢谢。这非常方便。复制列表的另一种方法是x=list(yourlist)@FredMitchell。这会创建一个浅拷贝,因此您仍然关心要复制的内容
deepcopy
以更复杂的嵌套类型(如
dict
s或
list
s)迭代深度复制所有项
grid = [x[:] for x in target]
from copy import deepcopy
grid = deepcopy(target)