List comprehension vs map

前端 未结 11 1852
长情又很酷
长情又很酷 2020-11-21 04:39

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

11条回答
  •  独厮守ぢ
    2020-11-21 05:00

    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 -mtimeit -s'xs=range(10)' 'map(hex, xs)'
    100000 loops, best of 3: 4.86 usec per loop
    $ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'
    100000 loops, best of 3: 5.58 usec per loop
    

    An example of how performance comparison gets completely reversed when map needs a lambda:

    $ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
    100000 loops, best of 3: 4.24 usec per loop
    $ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
    100000 loops, best of 3: 2.32 usec per loop
    

提交回复
热议问题