I have a list of tuples, lets say:
durations = [(1, 5), (2, 3), (1, 6), (3, 1), (3, 12), (7, 8)]
And want to perform a groupby operation on it, which returns the sums of the second tuple element for each tuple in the list. My desired output would look like this (preferably sorted descending by the second tuple element):
[(3, 13), (1, 11), (7, 8), (2, 3)]
However, when I tried the solution from Grouping Python tuple list:
import itertools
import operator
def accumulate(l):
it = itertools.groupby(l, operator.itemgetter(0))
for key, subiter in it:
yield key, sum(item[1] for item in subiter)
durations = [(1, 5), (2, 3), (1, 6), (3, 1), (3, 12), (7, 8)]
output = list(accumulate(durations))
I keep getting wrong output:
[(1, 5), (2, 3), (1, 6), (3, 13), (7, 8)]
(In this example it does not add up (1, 5) and (1, 6) to (1, 11). Running this code on larger data gives a lot of such missers)
How to solve this?