首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >numpy与Python map()中的矢量化

numpy与Python map()中的矢量化
EN

Stack Overflow用户
提问于 2019-09-14 16:59:06
回答 1查看 333关注 0票数 2

我在比较大数组的计算方法,并希望比较numpy中广播运营商的速度和替代方案的速度。不过,看到python map()函数的速度之快,我感到很惊讶,我想知道是否有人能解释一下为什么这比广播快得多。

广播

代码语言:javascript
复制
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = (farenheit - 32) * (5/9)

4.5s±99.4ns/环(平均±std )。dev.7次运行中,每一次循环100000次)

列表理解

代码语言:javascript
复制
%%timeit farenheit = np.linspace( -10, 20, 1000 )
[(temp - 32) * (5/9) for temp in farenheit]

886±4.56s/环(平均±std )。dev.7次运行中,每一次有1000次循环)

map() Python 3

代码语言:javascript
复制
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = map(lambda temp: (temp - 32) * (5/9), farenheit)

每环248 ns±41.9 ns (平均±std )。dev.7次运行中,每一次循环1000000次)

EN

回答 1

Stack Overflow用户

发布于 2019-09-14 17:06:02

map速度如此之快,因为它实际上没有运行计算。它不返回带有新值的新列表/数组,而是返回一个map对象(迭代器),该对象仅在需要项时才进行计算。

为了进行公平的比较,您应该在第一部分的末尾执行list(celcius)。只有到那时才能执行计算。如果您的lambda (或其他函数)在其中某个地方有一个print,那么您将看到map()本身还没有真正执行这些命令。

阅读有关maphttps://docs.python.org/3/library/functions.html#map的更多信息

举个例子:

代码语言:javascript
复制
def double(x):
    print('hi')
    return x*2

a = [1,2,3]
b = map(double, a)

# notice nothing is printing, the calculation isn't happening as well

c = list(b) # this will print 'hi' 3 times as well as returning the doubled list
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57937570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档