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

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

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

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

手掌心 2021-04-12 12:14:42
我有一個字典列表,需要使用另一個字典列表中的信息進(jìn)行更新。我當(dāng)前的解決方案(如下)的工作方式是從第一個列表中取出每個詞典,然后將其與第二個列表中的每個詞典進(jìn)行比較。它可以工作,但是有沒有更快,更優(yōu)雅的方法來達(dá)到相同的結(jié)果呢?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貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個贊

通過id使用第一個數(shù)組創(chuàng)建索引的字典。使用循環(huán)遍歷第二個數(shù)組id。


for replacement in b:

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

   if v is not None:

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

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


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

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個贊

與其進(jìn)行l(wèi)en(a)* len(b)循環(huán),不如將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}語法要求使用現(xiàn)代版本的Python(> = 3.5)。


查看完整回答
反對 回復(fù) 2021-04-27
?
揚(yáng)帆大魚

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超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


查看完整回答
反對 回復(fù) 2021-04-27
  • 3 回答
  • 0 關(guān)注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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