开发者

How do I sum the columns in 2D list?

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:

r开发者_开发问答ow_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]


Use zip

col_totals = [ sum(x) for x in zip(*my_list) ]


>>> 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]


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


[x + y for x, y in zip(*my_list)]


Use NumPy and transpose

import numpy as np
my_list = np.array([[1,2,3,4],[2,4,5,6]])
[ sum(x) for x in my_list.transpose() ]

Out[*]: [3, 6, 8, 10]

Or, simpler:

my_list.sum(axis = 0)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜