列表理解 vs 地图 [英] List comprehension vs map
问题描述
是否有理由更喜欢使用 map()
而不是列表理解,反之亦然?它们中的任何一个通常更有效还是被认为通常比另一个更 Pythonic?
Is there a reason to prefer using map()
over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic than the other?
推荐答案
map
在某些情况下可能会在微观上更快(当您不是为此目的制作 lambda,但使用相同的功能时在地图和列表中).在其他情况下,列表推导可能会更快,而且大多数(并非所有)pythonista 都认为它们更直接、更清晰.
map
may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.
使用完全相同的功能时地图的微小速度优势的示例:
An example of the tiny speed advantage of map when using exactly the same function:
$ python -m timeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -m timeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop
当 map 需要 lambda 时,性能比较如何完全颠倒的示例:
An example of how performance comparison gets completely reversed when map needs a lambda:
$ python -m timeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -m timeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop
这篇关于列表理解 vs 地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!