python - 我可以使用 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
所以我想知道是否可以对列表理解进行矢量化另外“对象不可调用”是什么意思?供将来参考 在此先感谢
解决方案
不要浪费时间尝试使用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] 快。
推荐阅读
- python - 如何计算一个df.column的时间值,是另一个df.column的一部分?
- bash - 为什么这个 for 循环在终端中运行而不是通过脚本运行?
- java - 以下代码的 selenium webdriver 中的空指针异常
- django - 我如何从views.py编辑/更改模型字段的值
- c# - 在Gridview中将Json数据抓取到字符串
- nginx - 使用 NGINX 为静态网站和 SPA (node.js) 提供服务
- java - Windows 机器上的默认 Java
- sql - 检测重复记录并用新记录 ID 标记旧记录
- python - 如何在 qcut 之后在分类变量中添加新类别?
- php - WordPress:警告:mysqli_real_connect():依赖系统的时区设置是不安全的