假设我有以下列表元组:
myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]
我想根据相同的第一个元组值对这个列表求和:
[(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求和元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16643514/