Home > Mobile >  How to sum second list from list of list in Python
How to sum second list from list of list in Python

Time:01-20

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]

CodePudding user response:

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.
print(res.tolist())
>> [ 9, 18, 27, 36, 45]

CodePudding user response:

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.

CodePudding user response:

This is really not 'python-like' solution, but I believe it will suit you well.

import numpy as np

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]]])

s = [0 for i in range(len(A[0]))]

for element in A:
    for i, ar in enumerate(element):
        s[i]  = sum(ar)

print(s)

CodePudding user response:

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]

CodePudding user response:

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])]

CodePudding user response:

result = [sum(x) for x in zip(*[y for y in arr])]
  • Related