How to sum a 2d array in Python?
This is yet another alternate Solution
In [1]: a=[[1, 2],[3, 4],[5, 6]]
In [2]: sum([sum(i) for i in a])
Out[2]: 21
I think this is better:
>>> x=[[1, 2],[3, 4],[5, 6]]
>>> sum(sum(x,[]))
21
You could rewrite that function as,
def sum1(input):
return sum(map(sum, input))
Basically, map(sum, input)
will return a list with the sums across all your rows, then, the outer most sum
will add up that list.
Example:
>>> a=[[1,2],[3,4]]
>>> sum(map(sum, a))
10