首页 > 解决方案 > 在 Python 列表中,为什么我附加的值与我附加的值不同?

问题描述

我有一个看起来像这样的垫子:

mat = [ [0,0,0,0], [6,7,8,9] ]

我想要一个看起来像这样的垫子列表:

[[1, 0, 0, 0], [6, 7, 8, 9]]
[[0, 1, 0, 0], [6, 7, 8, 9]]
[[0, 0, 1, 0], [6, 7, 8, 9]]
[[0, 0, 0, 1], [6, 7, 8, 9]]

这是我使用的代码:

# 2D List with some values
mat = [ [0,0,0,0], [6,7,8,9] ]

# append to listOfMats new a modified mat
# prints what I want listOfMats to look like
print("What listOfMats should look like:")
listOfMats = []
for x in range(4):
    mat[0][x] = 1
    print(mat)
    listOfMats.append(mat.copy())
    mat[0][x] = 0
print()

print("What I get for listOfMats: ")
for i in listOfMats:
    print(i)

这是输出:

What listOfMats should look like:
[[1, 0, 0, 0], [6, 7, 8, 9]]
[[0, 1, 0, 0], [6, 7, 8, 9]]
[[0, 0, 1, 0], [6, 7, 8, 9]]
[[0, 0, 0, 1], [6, 7, 8, 9]]

What I get for listOfMats: 
[[0, 0, 0, 0], [6, 7, 8, 9]]
[[0, 0, 0, 0], [6, 7, 8, 9]]
[[0, 0, 0, 0], [6, 7, 8, 9]]
[[0, 0, 0, 0], [6, 7, 8, 9]]

我认为问题出在这一行:

mat[0][x] = 1
print(mat)
listOfMats.append(mat.copy())
mat[0][x] = 0

mat[0][x] 更改为 1,然后我将该 mat 的深层副本附加到 listOfMats 中。但不知何故,那个附加的深拷贝被 mat[0][x] = 0 改变了。

我究竟做错了什么?

标签: pythonpython-3.x

解决方案


约翰的评论是正确的。我们需要这里列表的深层副本。

一种适用于任何类型列表的方法是使用该copy库:

import copy

mat_copy = copy.deepcopy(mat)

您的完整代码:

import copy

# 2D List with some values
mat = [ [0,0,0,0], [6,7,8,9] ]

# append to listOfMats new a modified mat
# prints what I want listOfMats to look like
print("What listOfMats should look like:")
listOfMats = []
for x in range(4):
    mat[0][x] = 1
    print(mat)
    listOfMats.append(copy.deepcopy(mat))
    mat[0][x] = 0
print()

print("What I get for listOfMats: ")
for i in listOfMats:
    print(i)

推荐阅读