Reputation: 427
I would like to sum from list of list as below
array([[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]]
What i want is to sum like below
[1,1,1]+[1,1,1]+[1,1,1] = 9
[2,2,2]+[2,2,2]+[2,2,2] = 18
.... = 27
= 36
= 45
And return a list like below as the final list:
[9,18,27,36,45]
Upvotes: 1
Views: 113
Reputation: 3633
You can use np.sum
a = np.array([[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]])
res = np.sum(a, axis=(0,2))
# Does reduction along axis 0 and 2 by doing summation.
# numpy takes tuple of axis indices to do reduction
# simultaneously along those axis.
print(res.tolist())
>> [ 9, 18, 27, 36, 45]
Upvotes: 5
Reputation: 39
a = [[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]]
result = [sum(x)+sum(y)+sum(z) for x,y,z in zip(a[0], a[1], a[1])]
Upvotes: -1
Reputation: 177
import numpy as np
lis=np.array([[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]])
print(lis.sum(axis=0).sum(axis=1))
easiest I think with numpy.
output
[ 9 18 27 36 45]
Upvotes: 1
Reputation: 2006
Using zip()
Code:
import numpy as np
lis=np.array([[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]],
[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]]])
res=[]
for i in zip(*lis):
res.append(sum(sum(i)))
print(res)
Output:
[9, 18, 27, 36, 45]
List comprehension:
print([sum(sum(i)) for i in zip(*lis)]) #Same output.
Upvotes: 0