I have a list of (label, count) tuples like this:
[('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)]
From that I want to sum all values with the same label (same labels always adjacent) and return a list in the same label order:
[('grape', 103), ('apple', 29), ('banana', 3)]
I know I could solve it with something like:
def group(l):
result = []
if l:
this_label = l[0][0]
this_count = 0
for label, count in l:
if label != this_label:
result.append((this_label, this_count))
this_label = label
this_count = 0
this_count += count
result.append((this_label, this_count))
return result
But is there a more Pythonic / elegant / efficient way to do this?
itertools.groupby
can do what you want:my version without itertools
[(k, sum([y for (x,y) in l if x == k])) for k in dict(l).keys()]
Method
Usage
You Convert to List of tuples like
list(group_by(my_list).items())
.output
Or a simpler more readable answer ( without itertools ):