python - 为什么设置字典列表的键/值对填充所有字典?
问题描述
test = [{}]*5 # Creates [{}, {}, {}, {}, {}]
print(test[1]) # outputs "{}"
test[1]['asdf'] = 5
print(test)
这给出test
了[{'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}]
. 不知何故,列表中的所有字典都被设置为相同的值
但是如果我们以不同的方式初始化列表,这不会发生:
test2 = [{} for i in range(5)] # Also [{}, {}, {}, {}, {}]
test2[1]['asdf'] = 1
print(test2)
test2
现在等于[{}, {'asdf': 1}, {}, {}, {}]
,预期的结果。
解决方案
两者之间的区别在于,对于[{}]*5
,Python 创建了一个 5 元素列表,其中包含方括号中给出的字典。IE。这是对同一词典的 5 种不同引用。
而另一种方法为列表中的每个元素创建一个新字典。
更详细的解释可以在重复的问题链接中找到
推荐阅读
- c++ - 从字符串的末尾开始获取反向子字符串
- node.js - 根据定义的模式在集合中进行比较时,Mongoose 是否隐式转换字段的类型?
- java - Spring boot @Async 注解抛出 LazyInitializationException
- json - 如何将嵌套的 Json 数组反序列化为字典?
- outsystems - 在使用 OutSystems 平台开发的移动应用程序中从 API 响应创建动态 UI(输入表单)
- firebase - Delphi 对 Firebase 实时数据库的 POST 请求
- r - 合并三个因子,使它们的因变量在 R 中求和
- javascript - 将两个数组与对象进行比较并显示删除了哪个项目
- c++ - 使用快速排序在 C++ 中排序可视化器错误
- node.js - 错误:发送 NodeJS Mongoose 后无法设置标头?