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 二维列表中具有相同第一个值的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)