第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

列表中的字典:使用 .update() 進行條件更新

列表中的字典:使用 .update() 進行條件更新

紅顏莎娜 2021-11-23 20:18:02
我正在嘗試使用條件更新nodes另一個列表中的元組列表中的字典source。元組列表:source = [('144 IV 285', 16), ('144 IV 1', 11), ('141 IV 155', 7)]字典列表:nodes = [{'id': '144 IV 285','date': '2018-08-15','relevancy': 10, 'outDegree': 18},{'id': '144 IV 240','date': '2016-08-15','relevancy': 4, 'outDegree': 10}]'nodes' 中的每一項都應該inDegree基于'source' 列表通過一個新的鍵 ( ) 值對進行擴展。我的代碼:for item in sources:    for item2 in nodes:        if item2["id"] == item[0]:            item2.update( {"inDegree": item[1]})        else:            item2.update( {"inDegree": 0})問題:inDegree如果“源”列表中的“節(jié)點”中的項目沒有匹配的 id,我如何通過源列表中的值或 0填充鍵?
查看完整描述

2 回答

?
慕娘9325324

TA貢獻1783條經(jīng)驗 獲得超4個贊

問題是source即使在匹配之后它也在迭代,因此覆蓋了以前的更新。您可以打開包裝source并進行比較:


for item2 in nodes:

    sources = list(zip(*source))

    if item2["id"] in sources[0]:

        item2.update({"inDegree": sources[1][sources[0].index(item2["id"])]})

    else:

        item2.update({"inDegree": 0})


print(nodes)

[{'id': '144 IV 285',

  'date': '2018-08-15',

  'relevancy': 10,

  'outDegree': 18,

  'inDegree': 16},

 {'id': '144 IV 240',

  'date': '2016-08-15',

  'relevancy': 4,

  'outDegree': 10,

  'inDegree': 0}]


查看完整回答
反對 回復 2021-11-23
?
慕的地10843

TA貢獻1785條經(jīng)驗 獲得超8個贊

嘗試這個:


for item in nodes:

    for item2 in source:

        if item["id"] == item2[0]:

            item.update( {"inDegree": item2[1]})

            break

        else:

            item.update( {"inDegree": 0})


查看完整回答
反對 回復 2021-11-23
  • 2 回答
  • 0 關(guān)注
  • 237 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號