我在 python 解释器中尝试了以下内容:
>>> a = []
>>> b = {1:'one'}
>>> a.append(b)
>>> a
[{1: 'one'}]
>>> b[1] = 'ONE'
>>> a
[{1: 'ONE'}]
Here, after appending the dictionary b
to the list a
, I’m changing the value corresponding to the key 1
in dictionary b
.这种变化也以某种方式反映在列表中。当我将字典附加到列表时,我不只是附加字典的值吗?看起来好像我已将指向字典的指针附加到列表中,因此对字典的更改也反映在列表中。
我不希望更改反映在列表中。我该怎么做?
原文由 neo29 发布,翻译遵循 CC BY-SA 4.0 许可协议
您是正确的,因为您的列表包含对原始词典的 _引用_。
a.append(b.copy())
应该可以解决问题。请记住,这是一个浅拷贝。另一种方法是使用
copy.deepcopy(b)
,它会进行深度复制。