python - 更新列表的元素,其中列表是字典中的值
问题描述
当我尝试更新列表的元素时,其中列表是字典中的值,它会更新字典中每个列表中该索引处的所有值。
示例代码:
dit = {}
d = {}
ls = ['hhh','ew']
a = "hhh"
b = "ew"
j = 3
dit[a] = [1,2,3,4]
dit[b] = [5,6,7,8]
const = [0,2,3,4]
d = dict.fromkeys(dit.keys() ,const)
print(d)
for i in ls:
print(i)
d[i][0] = max(d[i][0], j)
print(d)
j += 1
我得到的输出是:
{'hhh': [0, 2, 3, 4], 'ew': [0, 2, 3, 4]}
hhh
{'hhh': [3, 2, 3, 4], 'ew': [3, 2, 3, 4]}
ew
{'hhh': [4, 2, 3, 4], 'ew': [4, 2, 3, 4]}
所需的输出是:
{'hhh': [0, 2, 3, 4], 'ew': [0, 2, 3, 4]}
hhh
{'hhh': [3, 2, 3, 4], 'ew': [0, 2, 3, 4]}
ew
{'hhh': [3, 2, 3, 4], 'ew': [4, 2, 3, 4]}
解决方案
发生这种情况是因为您在每个 dict 元素上分配了 const 本身。当您更新此列表时,它将更新其所有出现。在您的代码中更改它,它将起作用:
d = dict.fromkeys(dit.keys() ,const)
至
d = {i:const.copy() for i in dit.keys()}
推荐阅读
- python - 如何限制 django lamba 查询中的响应大小
- html - CSS Grid 元素在容器外扩展
- json - 从 JSON 字典 Pyspark 创建非透视结构
- bash - 在 bash 中完成多个代码构建时如何显示和停止执行?
- c# - 布雷泽。Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 已添加具有相同键的项
- react-native - 使用钩子在 React Native 中获取视图尺寸
- c# - 从 appsettings.json 到 Entity Framework .NET Core 中的 OnConfiguring 方法的连接字符串
- python - 删除 Openpyxl 中的自动分页符
- gcc - 从构建场中构建的可执行文件的 .gcda-s 和本地构建的 .gcno-s 生成覆盖范围
- mongodb - 查询每个文档具有不同限制的最后一个文档