簡體   English   中英

具有相同鍵的兩個不同字典中的兩個特定值的總和

[英]Sum of two specific values in two different dicts with the same keys

我是 Python 的初學者,遇到以下問題:

我有兩個循環,產生兩個看起來像這樣的字典(當然,更長):

dict1 = {'Manubar': ['string', 'string2', 'string3', 222, 23, 45], 'Schorsch': ['string', 'string2', 'string3', 122, 65, 44]}

dict2 = {'Manubar': ['string', 'string2', 543, 21, 34], 'Schorsch': ['string', 'string2', 354, 10, 65]}

我現在想將 dict1 和 dict2 中相同鍵的最后一位數字相加/相乘,並創建一個應該如下所示的新 dict:

dict3 = {'Manubar': ['string', 'string2', 'string3', 222, 23, **79** ], 'Schorsch': ['string', 'string2', 'string3', 122, 65, **109**]}

我試圖合並這兩個字典,但這只是覆蓋了值。 如何將最后一位數字相加,然后將它們放入新的字典中?

在寫這個問題時,我想出了這個:

dict3 ={}
keylist=list(dict1.keys())
xxx = 0
for _ in keylist:
    key = keylist[xxx]
    dict3.update({key: [dict1[key][5] + dict2[key][4]]})
    xxx += 1
print(dict3)

但是感覺有點遲鈍。 如何改進我的代碼?

替代:

import pandas as pd
dict1 = {'Manubar': ['string', 'string2', 'string3', 222, 23, 45], 'Schorsch': ['string', 'string2', 'string3', 122, 65, 44]}
dict2 = {'Manubar': ['string', 'string2', 543, 21, 34], 'Schorsch': ['string', 'string2', 354, 10, 65]}
df1 = pd.DataFrame.from_dict(dict1, orient='index')
df2 = pd.DataFrame.from_dict(dict2, orient='index')
df1.loc[:,5] += df2.loc[:,4]
{i: list(v.values()) for i, v in df1.to_dict('index').items()}

比評論中提出的單行代碼稍微冗長,但效率更高:

dict3 = {}
for k in dict1:
    L = dict1[k].copy()
    L[-1] += dict2[k][-1]
    dict3[k] = L

這使:

{'Manubar': ['string', 'string2', 'string3', 222, 23, 79], 'Schorsch': ['string', 'string2', 'string3', 122, 65, 109]}

如果好奇,這里是我機器上的性能比較結果,使用timeit

long way:           0.275188707979396
comprehension way:  0.3881134579423815

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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