本文介紹了Python sum 二維列表中具有相同第一個(gè)值的元素的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在嘗試找到一種有效的方法來執(zhí)行以下操作:
I'm trying to find an efficient way to do the following:
我有這個(gè)樣本:
sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]]
并且需要
res = [['no', 6, 15], ['ja', 15, 18], ['ap',7,12]]
即將第一個(gè)元素相同的子列表的對應(yīng)值相加.
i.e. sum the corresponding values of the sublists where the first element is the same.
非常感謝
我的代碼是:
codes = list(set([element[0] for element in sample]))
res=[]
for code in codes:
aux=[code]
res01 = 0
res02 = 0
for element in sample:
if element[0] == code:
res01 += element[1]
res02 += element[2]
aux += [res01, res02]
res.append(aux)
推薦答案
使用defaultdict
:
>>> from collections import defaultdict
>>> d = defaultdict(lambda: [0,0], list())
>>> for a,b,c in sample:
d[a][0]+=b
d[a][1]+=c
#driver 值:
IN : sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]]
OUT : d = defaultdict(<function <lambda> at 0x7f4349f17620>,
{'no': [6, 15], 'ja': [15, 18], 'ap': [7, 12]})
由于輸出的結(jié)構(gòu)是這樣的,我建議您使用 dict
類型來存儲(chǔ)您的輸出,因?yàn)閷硖幚硭鼤?huì)更容易.
Since the output is structured as such, I would suggest you utilise the dict
type for storing your output as future processing with it will be easier.
如果您仍然希望輸出為 list
,只需映射 dict
,如下所示:
In case you still want the output as a list
, just map the dict
, as follows:
>>> [ [key]+ele for key,ele in d.items()]
=> [['no', 6, 15], ['ja', 15, 18], ['ap', 7, 12]]
這篇關(guān)于Python sum 二維列表中具有相同第一個(gè)值的元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!