Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

Google Python style guide

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

Deprecated Language Features: ... "Use list comprehensions and for loops instead of filter, map, and reduce. "

The explanation given : "We do not use any Python version which does not support these features, so there is no reason not to use the new styles."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...