这是python中map / lambda的简化版本吗?(Is this simplified version of map/lambda in python? [duplicate])

编程入门 行业动态 更新时间:2024-10-27 20:35:01
这是python中map / lambda的简化版本吗?(Is this simplified version of map/lambda in python? [duplicate])

这个问题在这里已有答案:

Python列表理解与 地图 10答案

对于数组a = [1, 2, 3, 4] map / lambda表达式:

f = map(lambda x : x + 32, a)

似乎我可以简化写作:

f = [x + 32 for x in a]

我想知道是否有任何区别。

This question already has an answer here:

List comprehension vs map 9 answers

For map/lambda expression with array a = [1, 2, 3, 4]:

f = map(lambda x : x + 32, a)

Seems I can simplify write as:

f = [x + 32 for x in a]

I am wondering whether there is any difference.

最满意答案

lambda往往是函数开销较慢的原因。 lambda也倾向于使代码更难以阅读。 你也可以计时:

#!/usr/bin/env python import time a = [1, 2, 3, 4] t1 = time.time() f = map(lambda x : x + 32, a) t2 = time.time()-t1 print t2 t3 = time.time() g = [x + 32 for x in a] t4 = time.time()-t3 print t4

此代码返回:

7.86781311035e-06 2.14576721191e-06

此外,我对较大的列表尝试了同样的事情,并且lambda表达所花费的时间几乎是两倍。

python -m timeit '[x + 32 for x in range(100000)]' >> 100 loops, best of 3: 6.67 msec per loop python -m timeit 'map(lambda x : x + 32, range(100000))' >> 100 loops, best of 3: 12.5 msec per loop

这是性能上的巨大差异。

lambda tends to be slower cause of the function's overhead. Also lambdas tend to make code more difficult to read. You can also time it:

#!/usr/bin/env python import time a = [1, 2, 3, 4] t1 = time.time() f = map(lambda x : x + 32, a) t2 = time.time()-t1 print t2 t3 = time.time() g = [x + 32 for x in a] t4 = time.time()-t3 print t4

This code returned:

7.86781311035e-06 2.14576721191e-06

Also I tried the same thing for larger lists and the time taken is almost double for lambda expression.

python -m timeit '[x + 32 for x in range(100000)]' >> 100 loops, best of 3: 6.67 msec per loop python -m timeit 'map(lambda x : x + 32, range(100000))' >> 100 loops, best of 3: 12.5 msec per loop

which is huge difference in performance.

更多推荐

本文发布于:2023-08-05 19:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1439047.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这是   版本   map   lambda   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!