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

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

用另一個詞典列表更新詞典列表。有沒有更快的方法?

用另一個詞典列表更新詞典列表。有沒有更快的方法?

手掌心 2021-04-12 12:14:42
我有一個字典列表,需要使用另一個字典列表中的信息進行更新。我當前的解決方案(如下)的工作方式是從第一個列表中取出每個詞典,然后將其與第二個列表中的每個詞典進行比較。它可以工作,但是有沒有更快,更優雅的方法來達到相同的結果呢?a = [ { "id": 1, "score":200 }, { "id": 2, "score":300 }, { "id":3, "score":400 } ]b = [ { "id": 1, "newscore":500 }, { "id": 2, "newscore":600 } ]# update a with data from bfor item in a:    for replacement in b:        if item["id"]==replacement["id"]:            item.update({"score": replacement["newscore"]})
查看完整描述

3 回答

?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

通過id使用第一個數組創建索引的字典。使用循環遍歷第二個數組id。


for replacement in b:

   v = lookup.get(replacement['id'], None)

   if v is not None:

      v['score'] = replacement['newscore']

這將O(n^2)問題轉化為O(n)問題。


查看完整回答
反對 回復 2021-04-27
?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

與其進行len(a)* len(b)循環,不如將b加工成更易于使用的東西:


In [48]: replace = {d["id"]: {"score": d["newscore"]} for d in b}


In [49]: new_a = [{**d, **replace.get(d['id'], {})} for d in a]


In [50]: new_a

Out[50]: [{'id': 1, 'score': 500}, {'id': 2, 'score': 600}, {'id': 3, 'score': 400}]

請注意,該{**somedict}語法要求使用現代版本的Python(> = 3.5)。


查看完整回答
反對 回復 2021-04-27
?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

清單理解:

[i.update({"score": x["newscore"]}) for x in b for i in a if i['id']==x['id']]
print(a)

輸出:

[{'id': 1, 'score': 500}, {'id': 2, 'score': 600}, {'id': 3, 'score': 400}]

定時:

%timeit [i.update({"score": x["newscore"]}) for x in b for i in a if i['id']==x['id']]

輸出:

100000 loops, best of 3: 3.9 μs per loop


查看完整回答
反對 回復 2021-04-27
  • 3 回答
  • 0 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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