List comprehension vs map

前端 未结 11 1857
长情又很酷
长情又很酷 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:11

    I tried the code by @alex-martelli but found some discrepancies

    python -mtimeit -s "xs=range(123456)" "map(hex, xs)"
    1000000 loops, best of 5: 218 nsec per loop
    python -mtimeit -s "xs=range(123456)" "[hex(x) for x in xs]"
    10 loops, best of 5: 19.4 msec per loop
    

    map takes the same amount of time even for very large ranges while using list comprehension takes a lot of time as is evident from my code. So apart from being considered "unpythonic", I have not faced any performance issues relating to usage of map.

提交回复
热议问题