Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sum the columns in 2D list?

Tags:

python

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] 
like image 276
Marty Avatar asked Jul 11 '10 12:07

Marty


People also ask

How do you sum a column in Python 2D list?

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.

How do I sum a list of columns in Python?

We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension. Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.


1 Answers

Use zip

col_totals = [ sum(x) for x in zip(*my_list) ] 
like image 109
Metalshark Avatar answered Sep 20 '22 06:09

Metalshark