按位置将函数数组应用于元素数组

applying array of function to array of elements by position

假设如下:

def x2(x):
    res=x*x
    return res

def tx(x):
    res=2*x
    return res

def x3(x):
    res=x*x*x
    return res

x=np.array([1,2,3])
f=np.array([x2,tx,x3])

我正在尝试 return 一个数组,即 array([x2(1),tx(2),x3(3)]) 而不使用 for 循环。 这在 python 中可能吗?

不,在一般情况下,Python级for循环是不可避免的。

不过你可以把它藏在后面 map + lambda:

res1 = list(map(lambda x: x[0](x[1]), zip((x2, tx, x3), x)))
res2 = np.array([x2(1), tx(2), x3(3)])

assert np.array_equal(res1, res2)

当然,这种情况推荐使用列表理解:

res = [func(var) for func, var in zip((x2, tx, x3), x)]

没有 objective 这样做的理由,但您可以这样做 :

@np.vectorize
def apply(f,x) : return  f(x)

那么 apply(f,x) 现在是 [1,4,27]