Python:更改嵌套列表中的值

0 python list

我正在寻找 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)
Run Code Online (Sandbox Code Playgroud)

我想要的结果是通过以下方式完成的:

b[0][0] = 4 
Run Code Online (Sandbox Code Playgroud)

但不是通过:

a[0][0] = 4 
Run Code Online (Sandbox Code Playgroud)

Roy*_*012 5

您创建的两个列表并不相同,这就是您看到不同结果的原因。

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]]
Run Code Online (Sandbox Code Playgroud)

最后一点 - 在我看来,这是一个很酷的问题。需要一秒钟才能了解发生了什么:)