亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數值添加到目標字典中的現有鍵也會更新源字典

將數值添加到目標字典中的現有鍵也會更新源字典

ibeautiful 2023-04-25 17:15:56
我正面臨字典這個奇怪的問題。我有 2 部詞典 source_dict 和 target_dict。source_dict 由它自己的邏輯組成。我正在嘗試使用 source_dict 派生 target_dict。下面是我的代碼。來源字典:  {  "t1": {    "t1c": 92074660,    "t1p": 92074660,    "t1l": 0,    "s1": {      "s1c": 1558475,      "s1p": 1558475,      "s1l": 0,      "s1t1": {        "s1t1c": 1558475,        "s1t1p": 1558475,        "s1t1l": 0      }    },    "s2": {      "s2c": 4439058,      "s2p": 4439058,      "s2l": 0,      "s2t1": {        "s2t1c": 83946,        "s2t1p": 83946,        "s2t1l": 0      },      "s2t2": {        "s2t2c": 4355112,        "s2t2p": 4355112,        "s2t2l": 0      }    }  }}預期的 target_dict : {  "c": 5341515,  "p": 5341515,  "l": 0,  "s1": {    "s1c": 5341515,    "s1p": 5341515,    "s1l": 0,    "s1t1": {      "s1t1c": 5341515,      "s1t1p": 5341515,      "s1t1l": 0    }  }}算術計算:c = source_dict(t1.t1c + t2.t2c + t3.t3c)s1c = source_dict(t1.s1.s1c + t2.s1.s1c + t3.s1.s1c)我的邏輯:for k, v in source_dict.items():    for s, offset in v.items():      if isinstance(offset, dict):        for tpc, val in offset.items():          if 'c' not in tpc and 'p' not in tpc and 'l' not in tpc:            if tpc not in target_dict[s].keys():              target_dict[s][tpc] = val            else:              target_dict[s][tpc]['c'] = target_dict[s][tpc]['c'] + val['c']              target_dict[s][tpc]['p'] = target_dict[s][tpc]['p'] + val['p']              target_dict[s][tpc]['l'] = target_dict[s][tpc]['l'] + val['l']問題:使用此邏輯,它也在更新 source_dict 中的值。我可以得到一些幫助來理解到底是什么地方出了問題,這使得 source_dict 得到新計算值的更新嗎?
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

source_dict雖然分配給 的位置不是很明顯,但我猜 python 將變量(尤其是or 或)視為指針target_dict的相同條件仍然適用。你只需要制作一個源字典。


查看完整回答
反對 回復 2023-04-25
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號