defaultdict 更改反映在列表中

defaultdict changes get reflected in list

我只是在尝试 defaultdict 并且我无法理解为什么更改 defaultdict (d[1]=2) 会导致列表 v 发生变化,尽管在值变化之前已经完成了追加。请帮助..

>>> d=defaultdict(int)
>>> d[1]=1
>>> d[2]=3
>>> v=[]
>>> v.append(d)
>>> v.append(d)
>>> v
[defaultdict(<type 'int'>, {1: 1, 2: 3}), defaultdict(<type 'int'>, {1: 1, 2: 3})]
>>> d[1]=2
>>> v
[defaultdict(<type 'int'>, {1: 2, 2: 3}), defaultdict(<type 'int'>, {1: 2, 2: 3})]
>>

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

这意味着您应该将 d 中的 shallow copy 添加到您的列表中:

v.append(d.copy())