这是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 answersFor 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 t4This code returned:
7.86781311035e-06 2.14576721191e-06Also 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 loopwhich is huge difference in performance.
更多推荐
发布评论