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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…