基于元组第一个值的python sum元组列表 [英] python sum tuple list based on tuple first value
本文介绍了基于元组第一个值的python sum元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下列表元组:
Suppose I have the following list tuples:
myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]
我想基于相同的第一个元组值对该列表求和:
I want to sum this list based on the same first tuple value:
[(n,m),(n,k),(m,l),(m,z)] = m*k + l*z
对于myList
sum = 2*5 + 3*6 = 28
我怎么能得到这个?
推荐答案
您可以使用collections.defaultdict
:
>>> from collections import defaultdict
>>> from operator import mul
>>> lis = [(0,2),(1,3),(2,4),(0,5),(1,6)]
>>> dic = defaultdict(list)
>>> for k,v in lis:
dic[k].append(v) #use the first item of the tuple as key and append second one to it
...
#now multiply only those lists which contain more than 1 item and finally sum them.
>>> sum(reduce(mul,v) for k,v in dic.items() if len(v)>1)
28
这篇关于基于元组第一个值的python sum元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文