python - 在 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 改变了。
我究竟做错了什么?
解决方案
约翰的评论是正确的。我们需要这里列表的深层副本。
一种适用于任何类型列表的方法是使用该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)
推荐阅读
- algorithm - 如何有效地检测和去除形状中的非连接线
- angular - 本地存储不保存数据
- java - 在java中将大数字字符串转换为整数
- python - 如何使用 opencv+python+picamera 找到两个彩色对象
- python - 如何使用 win32com 在 Python 电子邮件中插入 Pandas 变量
- python-3.x - 这个 opencv-python 代码有什么错误?
- python - Django postgres查询结果为不同的数据库字段获得不同的结果
- html - 同一类元素的量角器定位器
- spring-boot - 使用 Jasypt 加密的 Spring Boot 外部化配置(引导问题)
- kubernetes - 运行 kubectl 命令 Helm post install