久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

Python sum 二維列表中具有相同第一個(gè)值的元素

Python sum elements in 2d list with the same first value(Python sum 二維列表中具有相同第一個(gè)值的元素)
本文介紹了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)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區(qū)域周圍繪制一個(gè)矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個(gè)矩形邊界框中應(yīng)用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據(jù)文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 精品国产99| 夜夜骚 | 男人天堂国产 | 亚洲欧美在线观看 | 日本在线免费看最新的电影 | 日韩精品视频网 | 91精品国产综合久久婷婷香蕉 | 久久久成人一区二区免费影院 | 成人影院在线视频 | 亚洲高清电影 | 精品av| 日韩a在线| 96国产精品久久久久aⅴ四区 | 国产小视频在线看 | 国内av在线| 久久久精品综合 | 久久免费精彩视频 | 国产精品高清一区二区 | 色综合一区二区 | 天天色图 | 久久精品久久久久久 | 热久久性 | 欧美一区二区三区在线视频 | 久久久久国产一级毛片高清网站 | 99精品亚洲国产精品久久不卡 | 一区二区三区四区免费在线观看 | 欧美aa在线 | 亚洲五码久久 | 四虎最新地址 | 91精品国产91久久综合桃花 | av性色全交蜜桃成熟时 | 蜜桃视频在线观看www社区 | 一级片在线视频 | 日韩高清av| 中文字幕 在线观看 | 国产精品成人一区二区 | 欧美淫片 | 日韩精品在线观看一区二区 | 国内精品伊人久久久久网站 | 国产精品一区一区三区 | 国产一区二区黑人欧美xxxx |