tags:

views:

106

answers:

4

Say I've a Python 2D list as below:

my_list =  [ [1,2,3,4],
             [2,4,5,6] ]

I can get the row totals with a list comprehension:

row_totals = [ sum(x) for x in my_list ]

Can I get the column totals without a double for loop? Ie, to get this list:

[3,6,8,10]
+5  A: 
[x + y for x, y in zip(*my_list)]
Ignacio Vazquez-Abrams
The *my_list is a neat trick.
Metalshark
It's very neat. Never seen it before now...
Marty
+8  A: 

Use zip

col_totals = [ sum(x) for x in zip(*my_list) ]
Metalshark
I like this as it doesn't assume 2 rows.
Marty
+6  A: 
>>> map(sum,zip(*my_list))
[3, 6, 8, 10]

Or the itertools equivalent

>>> from itertools import imap, izip
>>> imap(sum,izip(*my_list))
<itertools.imap object at 0x00D20370>
>>> list(_)
[3, 6, 8, 10]
gnibbler
And we have a code golf winner!
Metalshark
+1  A: 

Solution map(sum,zip(*my_list)) is the fastest. However, if you need to keep the list, [x + y for x, y in zip(*my_list)] is the fastest.

The test was conducted in Python 3.1.2 64 bit.

>>> import timeit
>>> my_list = [[1, 2, 3, 4], [2, 4, 5, 6]]
>>> t1 = lambda: [sum(x) for x in zip(*my_list)]
>>> timeit.timeit(t1)
2.5090877081503606
>>> t2 = lambda: map(sum,zip(*my_list))
>>> timeit.timeit(t2)
0.9024796603792709
>>> t3 = lambda: list(map(sum,zip(*my_list)))
>>> timeit.timeit(t3)
3.4918002495520284
>>> t4 = lambda: [x + y for x, y in zip(*my_list)]
>>> timeit.timeit(t4)
1.7795929868792655
Selinap
Nice to know. Thanks for doing the speed test.
Metalshark