python sum tuple list based on tuple first value -
suppose have following list tuples:
mylist = [(0,2),(1,3),(2,4),(0,5),(1,6)] i want sum list based on same first tuple value:
[(n,m),(n,k),(m,l),(m,z)] = m*k + l*z for mylist
sum = 2*5 + 3*6 = 28 how can got this?
you can use collections.defaultdict:
>>> collections import defaultdict >>> operator import mul >>> lis = [(0,2),(1,3),(2,4),(0,5),(1,6)] >>> dic = defaultdict(list) >>> k,v in lis: dic[k].append(v) #use first item of tuple key , append second 1 ... #now multiply lists contain more 1 item , sum them. >>> sum(reduce(mul,v) k,v in dic.items() if len(v)>1) 28
Comments
Post a Comment