python - defaultdict 的更改会反射(reflect)在列表中

标签 python defaultdict

我只是尝试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 copyd 添加到您的列表中:

v.append(d.copy())

关于python - defaultdict 的更改会反射(reflect)在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394186/

相关文章:

python - 从 Python 中的 cx_Oracle PL/SQL 调用返回变量

python - 如何在 Django 模型中设置外键?

python - 在 Python 中将字典解析为电子表格

python : defaultdict every value is updated

Python:为什么 PostgreSQL 表中的列名用双引号引起来?

python - 需要在Python中不断监控串口数据

python - 如何将defaultdict转换为dict?

具有混合数据类型的 Python 嵌套 defaultdict

python - 将 .txt 文件转换为列表并能够逐行索引和打印列表