List comprehension vs map

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

    So since Python 3, map() is an iterator, you need to keep in mind what do you need: an iterator or list object.

    As @AlexMartelli already mentioned, map() is faster than list comprehension only if you don't use lambda function.

    I will present you some time comparisons.

    Python 3.5.2 and CPython
    I've used Jupiter notebook and especially %timeit built-in magic command
    Measurements: s == 1000 ms == 1000 * 1000 µs = 1000 * 1000 * 1000 ns

    Setup:

    x_list = [(i, i+1, i+2, i*2, i-9) for i in range(1000)]
    i_list = list(range(1000))
    

    Built-in function:

    %timeit map(sum, x_list)  # creating iterator object
    # Output: The slowest run took 9.91 times longer than the fastest. 
    # This could mean that an intermediate result is being cached.
    # 1000000 loops, best of 3: 277 ns per loop
    
    %timeit list(map(sum, x_list))  # creating list with map
    # Output: 1000 loops, best of 3: 214 µs per loop
    
    %timeit [sum(x) for x in x_list]  # creating list with list comprehension
    # Output: 1000 loops, best of 3: 290 µs per loop
    

    lambda function:

    %timeit map(lambda i: i+1, i_list)
    # Output: The slowest run took 8.64 times longer than the fastest. 
    # This could mean that an intermediate result is being cached.
    # 1000000 loops, best of 3: 325 ns per loop
    
    %timeit list(map(lambda i: i+1, i_list))
    # Output: 1000 loops, best of 3: 183 µs per loop
    
    %timeit [i+1 for i in i_list]
    # Output: 10000 loops, best of 3: 84.2 µs per loop
    

    There is also such thing as generator expression, see PEP-0289. So i thought it would be useful to add it to comparison

    %timeit (sum(i) for i in x_list)
    # Output: The slowest run took 6.66 times longer than the fastest. 
    # This could mean that an intermediate result is being cached.
    # 1000000 loops, best of 3: 495 ns per loop
    
    %timeit list((sum(x) for x in x_list))
    # Output: 1000 loops, best of 3: 319 µs per loop
    
    %timeit (i+1 for i in i_list)
    # Output: The slowest run took 6.83 times longer than the fastest. 
    # This could mean that an intermediate result is being cached.
    # 1000000 loops, best of 3: 506 ns per loop
    
    %timeit list((i+1 for i in i_list))
    # Output: 10000 loops, best of 3: 125 µs per loop
    

    You need list object:

    Use list comprehension if it's custom function, use list(map()) if there is builtin function

    You don't need list object, you just need iterable one:

    Always use map()!

提交回复
热议问题