I have a list of (label, count) tuples like this:
[(\'grape\', 100), (\'grape\', 3), (\'apple\', 15), (\'apple\', 10), (\'apple\', 4), (\'banana\', 3)]
itertools.groupby
can do what you want:
import itertools
import operator
L = [('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10),
('apple', 4), ('banana', 3)]
def accumulate(l):
it = itertools.groupby(l, operator.itemgetter(0))
for key, subiter in it:
yield key, sum(item[1] for item in subiter)
>>> print list(accumulate(L))
[('grape', 103), ('apple', 29), ('banana', 3)]
>>>