久久久久久久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 類型來存儲您的輸出,因?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 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 欧美xxxx性xxxxx高清 | 色一情一乱一伦一区二区三区 | 国产精品久久国产精品 | 在线视频 欧美日韩 | 一区二区三区在线播放 | 成人教育av| 理伦毛片 | 九九热在线精品视频 | 午夜精品一区二区三区在线观看 | 成人av电影免费在线观看 | 欧美日韩国产一区二区三区 | 91天堂| 99久久久无码国产精品 | 日韩a| 神马久久av| 在线a视频网站 | 8x国产精品视频一区二区 | 中文字幕亚洲视频 | 密室大逃脱第六季大神版在线观看 | 国产999精品久久久 精品三级在线观看 | 日日骚视频| 久久亚洲一区 | 日韩精品在线播放 | 亚洲欧美视频一区 | 日韩在线中文字幕 | 在线免费观看色 | 亚洲国产一区在线 | 亚洲高清视频一区二区 | 狠狠综合久久av一区二区老牛 | 久久国产秒 | 韩国av一区二区 | 欧美成人激情视频 | 亚洲精品1区 | 九九久久久 | 精品一区二区三区中文字幕 | 国产一区二区三区在线免费 | 久久久国产一区二区三区 | 国产人成在线观看 | 亚洲免费观看 | 欧美精品二区 | 亚洲色图综合 |