首页 > 解决方案 > 我可以使用 np.vectorize() 对列表理解进行矢量化吗?

问题描述

我对 Python 相当陌生,从NumPy.
我尝试执行以下操作:

a = np.arange(1, 20)  
f = np.vectorize([x/(x+1) for x in a])  
f(a)  
TypeError: 'list' object is not callable <-- got this error

所以我想知道是否可以对列表理解进行矢量化另外“对象不可调用”是什么意思?供将来参考 在此先感谢

标签: pythonpython-3.xnumpyvectorization

解决方案


不要浪费时间尝试使用np.vectorize,尤其是当您可以进行真正的numpy 矢量化时。不要被名字所迷惑。这不是快速数值计算的捷径。

In [442]: a = np.arange(1,5)

你的列表理解:

In [443]: [x/(x+1) for x in a]
Out[443]: [0.5, 0.6666666666666666, 0.75, 0.8]

可以通过简单的 numpy 数组操作来完成:

In [444]: a/(a+1)
Out[444]: array([0.5, 0.66666667, 0.75, 0.8])

但是让我们假设我们有一个只适用于标量输入的函数:

In [445]: f = np.vectorize(lambda x: x/(x+1), otypes=[float])
In [446]: f(a)
Out[446]: array([0.5, 0.66666667, 0.75 , 0.8])

它可以工作,但它比 [444] 慢得多,并且不比 [443] 快。


推荐阅读