Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Python tuple list

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?

like image 305
hoju Avatar asked Feb 12 '10 01:02

hoju


People also ask

How do you combine tuples and lists in Python?

Join the tuples in the list using map(join_tuple_string, list) method. Convert the result to list. Print the result.

Can you concatenate list and tuple?

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)).

How do you combine tuples in Python?

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.


1 Answers

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)] 
like image 117
Thomas Wouters Avatar answered Sep 23 '22 20:09

Thomas Wouters