簡體   English   中英

字典列表中的索引會影響所有字典

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM