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

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

Python sum elements in 2d list with the same first value(Python sum 二維列表中具有相同第一個值的元素)
本文介紹了Python sum 二維列表中具有相同第一個值的元素的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在嘗試找到一種有效的方法來執行以下操作:

I'm trying to find an efficient way to do the following:

我有這個樣本:

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]]

即將第一個元素相同的子列表的對應值相加.

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]})

由于輸出的結構是這樣的,我建議您使用 dict 類型來存儲您的輸出,因為將來處理它會更容易.

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]]

這篇關于Python sum 二維列表中具有相同第一個值的元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 久久99免费视频 | 毛片中文字幕 | 中国一级黄色 | 国产亚洲欧美一区二区 | 成人免费黄色片 | 99国产精品99久久久久久粉嫩 | 四虎视频在线观看 | 国产精品suv一区二区 | 成人午夜激情视频 | 91性高潮久久久久久久久 | 国产成年人视频 | 狠狠婷婷 | 亚洲一区不卡 | www.婷婷| 在线午夜视频 | 特黄一级视频 | 精品视频网站 | 日韩久久久久久 | www.久草.com | 一区二区黄色 | 国产精品成人免费视频 | 色激情网 | 日韩色在线 | 少妇一级片 | 在线中文av| 国产伦精品一区二区三区视频网站 | 福利色导航 | 日本国产一区 | 欧美一区二区在线 | 可以看的毛片 | 91狠狠综合 | 成年网站在线观看 | 亚洲一区二区在线播放 | 在线观看欧美日韩 | 中文字幕一区二区三区乱码 | 欧美精品成人 | 天天干天天操 | 做爰xxxⅹ性生交 | 国产欧美在线观看 | 狠狠干天天干 | 国产高清视频 |