Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum second list from list of list in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[9,18,27,36,45]

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading