假设我有以下列表元组:
myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]
我想根据相同的第一个元组值对该列表求和:
[(n,m),(n,k),(m,l),(m,z)] = m*k + l*z
For 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)