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

Replace for loop that indexes two arrays and applies a function on each row

I have a for-loop that works on two values and I would like to apply it in a faster way or vectorise it if possible. My original for-loop looks something like this

import numpy as np

x = [1,2,3]
y = [0,0,0]

for i in range(len(x)):
    
    # index value in each element
    xi = x[i]
    yi = y[i]
    
    # apply function some bivariate function
    print(np.sum(xi,yi))

I was thinking maybe I could use the list approach but the output came out as below.

x = [1,2,3]
y = [0,0,0]

[np.sum(i, j) for i in x for j in y]
# output
[1, 1, 1, 2, 2, 2, 3, 3, 3]

What are better methods to replace the initial for-loop statement? My actual function is not a sum as in the initial example, that is just a dummy function.

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

>Solution :

IIUC, use zip

>>> [np.sum(i, j) for i, j in zip(x, y)]
[1, 2, 3]
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