为什么
f = g = h = []
f.append(1)
make
f = [1], g=[1], h=[1]
?
为什么列表如此链接?如果我对整数变量做同样的事情,它们将不会被链接。
[[]
在特定位置创建一个列表。
然后,将h
指向该位置。
然后,您也将g
指向该位置。和f
。
自然地,当您就地修改该列表(不更改其引用)时,指向它的所有内容都将看到更改。
您说更改整数不会产生这种效果。那是因为这是另一种变化。 python中的整数是不可变的,通常不能就地更改-而是必须创建一个新的整数(以及它的新引用),然后将其分配给查看旧整数的名称:
h = 5
id(h)
# 4318792464
h = 6
id(h)
# 4318792496
# note that these two addresses are different, meaning different locations.
如果这意味着旧值永远丢失,那么垃圾收集器将最终清理它并释放它所占用的内存。
如您所见,就地修改列表不会更改其引用:
f = g = []
id(f) == id(g)
# True
g.append(1)
id(f) == id(g)
# still True
g = [1] # make a new list at a different location, with the same value
f == g
# True
id(f) == id(g)
# False