Skip to content Skip to sidebar Skip to footer

Python Sum Tuple List Based On Tuple First Value

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

Solution 1:

You can use 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() iflen(v)>1)
 28

Solution 2:

from operator import itemgetter
from itertools import groupby

defmul(args): # will work with more than 2 arguments, e.g. 2*3*4return reduce(lambda acc, x: acc*x, args, 1)

myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]
sorted_ = sorted(myList, key=itemgetter(0))
grouped = groupby(sorted_, key=itemgetter(0))
numbers = [[t[1] for t in items] for _, items in grouped]
muls = [mul(items) for items in numbers iflen(items) > 1]
printsum(muls)

Solution 3:

This solution does it in a single pass as opposed to the more readable defaultdict version which takes two passes and may take more space:

myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]
sum_ = 0
once, twice = {}, {}
for x, y in myList:
    if x in once:
        sum_ -= twice.get(x, 0)
        twice[x] = twice.get(x, once[x]) * y
        sum_ += twice[x]
    else:
        once[x] = y


>>> sum_
28

Post a Comment for "Python Sum Tuple List Based On Tuple First Value"