二维列表中的Python sum元素具有相同的第一个值 [英] Python sum elements in 2d list with the same first value

查看:34
本文介绍了二维列表中的Python sum元素具有相同的第一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种有效的方法来执行以下操作:

我有这个样本:

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

即对第一个元素相同的子列表的对应值求和.

非常感谢

我的代码是:

codes = list(set([element[0] for element in sample]))资源=[]对于代码中的代码:辅助=[代码]res01 = 0res02 = 0对于样本中的元素:如果元素[0] == 代码:res01 += 元素[1]res02 += 元素[2]辅助 += [res01, res02]res.append(aux)

解决方案

Using defaultdict:

<预><代码>>>>从集合导入 defaultdict>>>d = defaultdict(lambda: [0,0], list())>>>对于样本中的 a、b、c:d[a][0]+=bd[a][1]+=c

#driver 值:

IN : sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]]OUT : d = defaultdict( at 0x7f43​​49f17620>,{'no': [6, 15], 'ja': [15, 18], 'ap': [7, 12]})

由于输出的结构是这样的,我建议您使用 dict 类型来存储您的输出,以便将来处理它会更容易.

如果您仍然希望输出为 list,只需映射 dict,如下所示:

<预><代码>>>>[ [key]+ele for key,ele in d.items()]=>[['不', 6, 15], ['ja', 15, 18], ['ap', 7, 12]]

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

I have this sample:

sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]]

and would need

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.

Thanks a lot

My code is:

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) 

解决方案

Using 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 values :

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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆