0

I want to add the

distances
[array([2.0786226e-03, 3.9023757e-03, 3.4480095e-03, 5.1999092e-04], dtype=float32), array([0.0031136 , 0.00344056, 0.00739563, 0.0311079 ],
      dtype=float32), array([1.8880665e-03, 3.0295253e-03, 4.0802956e-03, 2.6324868e-02], dtype=float32), array([0.00330418, 0.00431347, 0.00802791, 0.00426304],
      dtype=float32)]

Desired Output

[0.00994899872, 0.04505769, 0.0353227554, 0.0199086]

I tried the following but it adds all the elements and gives on scalar value

print(sum( sum(x) if isinstance(x, list) else x for x in L ))  
1
  • What else would you expect sum to do? Commented Jul 9, 2021 at 2:04

4 Answers 4

3

You could use numpy to do this, as

import numpy as np

distances = np.array([[2.0786226e-03, 3.9023757e-03, 3.4480095e-03, 5.1999092e-04],
                     [0.0031136 , 0.00344056, 0.00739563, 0.0311079 ],
                     [1.8880665e-03, 3.0295253e-03, 4.0802956e-03, 2.6324868e-02],
                     [0.00330418, 0.00431347, 0.00802791, 0.00426304]],dtype=np.float32)

print(np.sum(distances,axis=1))

which gives the desired output

Sign up to request clarification or add additional context in comments.

4 Comments

My array has dtype=float32 which is not present in your distances array
All sub_arrays have dtype=np.float32
There also, they just doesn't stay explicity outside as yours, but you could check that out by yourself taking distances[0], that is a float32 array, as all the others.
note that you could also define each of the arrays as a 4 dimensional array with dtype=np.float32 and in the distances you could assembly them all together and do the same operation using np,.sum, but this of course it is up to you.
1

Assuming L is distances, you were almost there:

print([sum(x) if isinstance(x, list) else x for x in L ])  

Comments

1

Before we continue, I would like to mention you should specify that it is with numpy.

Why make a one-liner? Use a simple for loop. Take the first item in each and every list and add them up separately. To then store it, append it in a list and move on to the second item. After you find a working code, then only try shortening it. This is a good python practice.

Comments

0

As you already have numpy objects inside your list you can sum these objects.

The numpy object array have the element wise implementation, so you can sum:

a = np.array([a1, a2, a3])
b = np.array([b1, b2, b3])
a + b

The result of a + b will be:

[a1+b1, a2+b2, a3+b3]

As @bruno mentioned you can use the built in method numpy.sum to do this automatically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.