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?
Join the tuples in the list using map(join_tuple_string, list) method. Convert the result to list. Print the result.
Python concatenate tuples in a list. Here, we will see how to concatenate tuples in a list. The join() function is used to join each tuple element with each other, and list comprehension is used to handle the task of iteration through tuples. To get the output, I have used print(“The tuple in list is: ” + str(s)).
Concatenating and Multiplying TuplesConcatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple. The * operator can be used to multiply tuples.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With