Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulate items in a list of tuples

I have a list of tuples that looks like this:

lst = [(0, 0), (2, 3), (4, 3), (5, 1)]

What is the best way to accumulate the sum of the first and secound tuple elements? Using the example above, I'm looking for the best way to produce this list:

new_lst = [(0, 0), (2, 3), (6, 6), (11, 7)]

I am looking for a solution in Python 2.6

like image 673
user1728853 Avatar asked May 07 '13 17:05

user1728853


1 Answers

I would argue the best solution is itertools.accumulate() to accumulate the values, and using zip() to split up your columns and merge them back. This means the generator just handles a single column, and makes the method entirely scalable.

>>> from itertools import accumulate
>>> lst = [(0, 0), (2, 3), (4, 3), (5, 1)]
>>> list(zip(*map(accumulate, zip(*lst))))
[(0, 0), (2, 3), (6, 6), (11, 7)]

We use zip() to take the columns, then apply itertools.accumulate() to each column, then use zip() to merge them back into the original format.

This method will work for any iterable, not just sequences, and should be relatively efficient.

Prior to 3.2, accumulate can be defined as:

def accumulate(iterator):
    total = 0
    for item in iterator:
        total += item
        yield total

(The docs page gives a more generic implementation, but for this use case, we can use this simple implementation).

like image 169
Gareth Latty Avatar answered Sep 28 '22 06:09

Gareth Latty