Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sum a column of a list?

I have a Python array, like so:

[[1,2,3],
 [1,2,3]]

I can add the row by doing sum(array[i]), how can I sum a column, using a double for loop?

I.E. for the first column, I could get 2, then 4, then 6.

like image 948
MarJamRob Avatar asked Mar 12 '13 02:03

MarJamRob


People also ask

How do I sum a column in a list 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.

How do you sum data in a list?

sum() function in Python Sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.


2 Answers

Using a for loop (in a generator expression):

data = [[1,2,3],
        [1,2,3]]

column = 1
print(sum(row[column] for row in data))  # -> 4
like image 98
martineau Avatar answered Oct 21 '22 02:10

martineau


Try this:

a = [[1,2,3],
     [1,2,3]]

print [sum(x) for x in zip(*a)]

zip function description

like image 29
Artsiom Rudzenka Avatar answered Oct 21 '22 02:10

Artsiom Rudzenka