Kevin London
Kevin London

Reputation: 4728

Two sums from one list

I'd like to get the sums for two different values in a list. For example:

sample = [(1,3), (4,5), (8,2)]

I'd like the output to be

13, 10

I could do it in a couple of different ways. Here's how I have it currently:

t1 = 0
t2 = 0
for item1, item2 in sample:
    t1 += item1
    t2 += item2

What would be a more Pythonic way to solve this?

Upvotes: 3

Views: 159

Answers (5)

Joseph Dunn
Joseph Dunn

Reputation: 1308

A one-liner:

sum([ x[0] for x in sample ]), sum([ x[1] for x in sample ])

Or for lists of unknown dimension:

map(lambda i: sum(x[i] for x in sample), range(len(sample[0])))

Upvotes: 2

CT Zhu
CT Zhu

Reputation: 54380

If you are going to do this a lot (on big datasets), numpy will be helpful.

>>> from numpy import *
>>> sample = [(1,3), (4,5), (8,2)]
>>> sum(array(sample), axis=1)
array([ 4,  9, 10])
>>> sum(array(sample), axis=0)
array([13, 10])

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 602635

A functoinal approach:

from operator import add
from functools import partial
sample = [(1,3), (4,5), (8,2)]
result = reduce(partial(map, add), sample)

result will be the list [13, 10] after running this code.

Upvotes: 3

FastTurtle
FastTurtle

Reputation: 2311

You can try this:

from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = map(sum, izip(*sample))

You can also use a list comprehension instead of map.

from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = [sum(t) for t in izip(*sample)]

And you can deal with more than two sums:

from itertools import izip
sample = [(1, 3, 1), (4, 5, 1), (8, 2, 1)]
sums = [sum(t) for t in izip(*sample)]
# sums == [13, 10, 3]

Upvotes: 7

Brad Peabody
Brad Peabody

Reputation: 11417

sample = [(1,3), (4,5), (8,2)]

r1 = 0
r2 = 0
for v in sample:
    r1, r2 = r1+v[0], r2+v[1]

print r1, r2

Although @FastTurtle's is cooler.

Upvotes: 2

Related Questions