0

I have a python 2D function f(x,y) that returns a number for every pair x and y. I need to calculate f(x,y) having the elements in a list x=[x0,x1,x2,x3], y=[y0,y1,y2,y3] to obtain [f(x0,y0),f(x1,y1),f(x2,y2),f(x3,y3)]. I am doing this task with a for loop

result=[]
for k in range(len(k)):
    result.append(f(x[i],y[i]))

Is there a more pythonic way to do this?if possible with numpy arrays. Many thanks

flakes
  • 21,558
  • 8
  • 41
  • 88

1 Answers1

0

Using numpy is a good idea.

import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([2, 4, 6, 8])

def f(x, y):
    return x*y

z = f(x,y)
print(z) # array([ 0,  4, 12, 24])
Nabil Daoud
  • 221
  • 1
  • 10
  • 2
    Dependencies aren't free, don't use them if you can do without. I would only do this if I already had numpy in the dependencies, or if it was found to be computationally expensive without it. This would add about 10 to 15MB of bloat to your install size. – flakes Nov 17 '20 at 23:22
  • And several seconds to startup time, IMX. – Karl Knechtel Nov 17 '20 at 23:38