python - Python:更改嵌套列表中的值
问题描述
我正在寻找 Python 列表的初学者帮助。我创建了两个相同的列表 a 和 b,但方式不同。然后我尝试以相同的方式更改列表中的一个值。为什么我得到两个列表的不同结果?
见代码:
a = [[0] * 3] * 4
b = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
print(a, id(a))
print(b, id(b))
print(a == b)
a[0][0] = 4
b[0][0] = 4
print(a, id(a))
print(b, id(b))
print(a == b)
我想要的结果是通过:
b[0][0] = 4
但不是:
a[0][0] = 4
解决方案
您创建的两个列表不相同,这就是您看到不同结果的原因。
a = [[0]*3]*4 # four copies of the same list
b = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]] # four different lists, all
# three containing zeros.
[id(x) for x in a]
[4953622320, 4953622320, 4953622320, 4953622320]
# note - all are the same instance.
[id(x) for x in b]
[4953603920, 4953698624, 4953602240, 4953592848]
# note - all are the different instances
b[0][0] = 4 # change just one list
[[4, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
a[0][0] = 4 # change one list, but since a contains four references
# to this list it seems as if four lists were modified.
[[4, 0, 0], [4, 0, 0], [4, 0, 0], [4, 0, 0]]
最后一点——在我看来,这是一个很酷的问题。花点时间了解发生了什么:)