'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.
Solution 1:[1]
Here you go. - Use the zip function in such cases
list_sum = [np.sum(x,y) for x,y in zip(x,y)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rama |
