python - 我可以使用 np.vectorize() 对列表理解进行矢量化吗?

标签 python python-3.x numpy vectorization

我对 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

所以我想知道是否可以对列表理解进行向量化 另外“对象不可调用”是什么意思?备查 提前致谢

最佳答案

不要浪费时间尝试使用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])

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

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] 快不了多少。

关于python - 我可以使用 np.vectorize() 对列表理解进行矢量化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60201113/

相关文章:

python - 为什么 Matlab interp1 产生的结果与 numpy interp 不同?

c++ - 在 pythonQt 中使用 numpy 模块

python - 如何从一系列数组构建 Pandas 数据框

python - 从虚拟环境中在 PyCharm 中注册 VCS 根?

python - 参数 'on_delete' 没有值

python-3.x - 根据另一列的进度值创建数据框列?

python-3.x - 显示格式化的未评估 = 在 ipython 笔记本中使用 sympy 评估

python - QLineEdit 更改边框颜色而不更改边框样式

python - 为什么在初始化期间这是python语法错误?

python - 根据最近距离找到最佳的唯一邻居对