[英]Indexing in a list of dictionaries affects all the dictionaries
我列出了如下字典。
num=5
core_dict ={'c1':[0]*num , 'c2':[0]*num}
link=[core_dict]*3
这给出了(正确的)output:
[ {'c1': [0, 0, 0, 0, 0], 'c2': [0, 0, 0, 0, 0]}, #represents link1 for me
{'c1': [0, 0, 0, 0, 0], 'c2': [0, 0, 0, 0, 0]}, #represents link2 for me
{'c1': [0, 0, 0, 0, 0], 'c2': [0, 0, 0, 0, 0]}] #represents link3 for me
然后我想替换 link2 的'c1'
值。 我愿意:
link[1]['c1']=[10]*num
但这会更改列表中每个字典的'c1'
键的值。 我怎样才能做索引只影响一本字典?
[ {'c1': [10, 10, 10, 10, 10], 'c2': [0, 0, 0, 0, 0]}, #represents link1 for me
{'c1': [10, 10, 10, 10, 10], 'c2': [0, 0, 0, 0, 0]}, #represents link2 for me
{'c1': [10, 10, 10, 10, 10], 'c2': [0, 0, 0, 0, 0]}] #represents link3 for me
您的link
初始化将每个元素指向同一个字典(即内存中的相同位置):
而不是使用:
link=[core_dict]*3
利用
from copy import deepcopy
link=[deepcopy(core_dict) for _ in range(3)]
这样每个字典使用的memory就完全分开了。
您也可以在不导入deepcopy
的情况下创建这样的link
:
link=[core_dict.copy() for i in range(3)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.