我只是尝试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.
这意味着您应该附加 shallow copy将 d
添加到您的列表中:
v.append(d.copy())
关于python - defaultdict 的更改会反射(reflect)在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394186/