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]
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.
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.
Use zip
col_totals = [ sum(x) for x in zip(*my_list) ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With