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

Time:02-10

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.

CodePudding user response:

IIUC, use zip

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

CodePudding user response:

Here you go. - Use the zip function in such cases

list_sum = [np.sum(x,y) for x,y in zip(x,y)]
  • Related