Google Python style guide

前端 未结 4 934
南旧
南旧 2020-11-30 01:44

Why does the Google Python Style Guide prefer list comprehensions and for loops instead of filter, map, and reduce?

Deprecated Language Features: ... \"Use list com

4条回答
  •  野性不改
    2020-11-30 02:05

    The Google Python Style guide does not say

    prefer list comprehensions and for loops instead of filter, map, and reduce

    Rather, the full sentence reads,

    Use list comprehensions and for loops instead of filter and map when the function argument would have been an inlined lambda anyway. (my emphasis)

    So it is not recommending that you completely avoid using map, for instance -- only that

    [expression(item) for item in iterable] 
    

    is preferable to

    map(lambda item: expression(item), iterable)
    

    In this case it is clear that the list comprehension is more direct and readable.

    On the other hand, there is nothing wrong with using map like this:

    map(str, range(100))
    

    instead of the longer-winded

    [str(item) for item in range(100)]
    

    It performs well to boot:

    In [211]: %timeit list(map(str,range(100)))
    7.81 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    In [215]: %timeit [str(item) for item in range(100)]
    10.3 µs ± 3.06 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

提交回复
热议问题