Consider I have a list of lists as:
[[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 indexes of first list's index wise and then the 2nd list 5+15+34=54 10+10+20=40
and so on 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 the list of lists.
But it gives sum of each list item as:
[6,19,55,73,181]
[25,11,35,27,89]
[43,40,35,40,110]
To sum a list of lists: Use the zip function to get an iterator of tuples with the corresponding items. Use a list comprehension to iterate over the iterable. On each iteration, pass the tuple to the sum() function.
Use zip() to add two lists element-wise Pass both lists into zip(*iterables) to get a list of tuples that pair elements with the same position from both lists. Use a for loop to add these elements together and append them to a new list. Use a list comprehension for a more compact implementation.
You are almost correct, you need to unpack results
and zip 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 list comprehension as
>>> [[sum(item) for item in zip(*items)] for items in zip(*data)]
[[54, 40, 50, 50, 200], [20, 30, 75, 90, 180]]
This is much easier 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
You can also use map()
, instead.
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 unnecessarily long and @thefourtheye's answer is better.
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