Sum of multiple index lists

I have a list of lists like:

[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]] [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]] [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]] 

Now I want the sum of all index indices of the first list to be wise, and then the second list 5+15+34=54 10+10+20=40 , etc. as:

 [54,40,50, 50,200], [20,30,75,90,180] 

I tried:

 for res in results: print [sum(j) for j in zip(*res)] 

Here results is a list of lists. But it gives the sum of each list item as:

 [6,19,55,73,181] [25,11,35,27,89] [43,40,35,40,110] 
+8
python list
source share
3 answers

You are almost right, you need to unzip the results and fix it as well.

 >>> data = [[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]], ... [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]], ... [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]] >>> for res in zip(*data): ... print [sum(j) for j in zip(*res)] ... [54, 40, 50, 50, 200] [20, 30, 75, 90, 180] 

You can simply write this with a list comprehension of how

 >>> [[sum(item) for item in zip(*items)] for items in zip(*data)] [[54, 40, 50, 50, 200], [20, 30, 75, 90, 180]] 
+8
source share

This is much simpler if you use Numpy:

 import numpy as np data = [[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]], [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]], [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]] a = np.array(data) print a.sum(axis=0) 

Output:

 [[ 54, 40, 50, 50, 200], [ 20, 30, 75, 90, 180]] 

Similarly:

 In [5]: a.sum(axis=1) Out[5]: array([[ 6, 19, 55, 73, 181], [ 25, 11, 35, 27, 89], [ 43, 40, 35, 40, 110]]) In [6]: a.sum(axis=2) Out[6]: array([[169, 165], [121, 66], [104, 164]]) In [7]: a.sum() Out[7]: 789 
+2
source share

You can also use map() .

 a = [[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]] b = [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]] c = [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]] results = [] for i in range(0, max(len(a), len(b), len(c))): results.append(map(lambda x, y, z: x + y + z, a[i], b[i], c[i])) for result in results: for i in result: print(i) 

But this is not necessarily long, and @thethe best answer is better.

+1
source share

All Articles