关于
Python list comprehension 其实就是 generator.
该怎么理解?
另外 map filter、generator 也让人挺不解的,求python 大牛都给解释下。这么设计的缘由是什么?
伊谢尔伦2017-04-17 13:46:40
First of all, regarding the sentence quoted in the question: Don’t understand it this way, it will get yourself involved, and it is also inaccurate.
This question needs to be looked at simply. For a simple list comprehension [x**2 for x in range(10)]
, it is equivalent to:
l = []
for x in range(10):
l.append(x**2)
So, list comprehension is just a syntax sugar that can make the initialization of the container more concise, but it is still essentially stuffing things into the container. (Of course, due to the existence of this syntax, python can also optimize performance in a targeted manner, and the performance will be better than its own append
)
List comprehensions provide a concise way to create lists.
List comprehensions provide a concise and concise way to createlist
.
From python official documentation
It is different from the concept of generator. If anything, iterator may be the correct way to describe x**2 for x in range(10)
this syntax, although its name is indeed generator expression.
Secondly, what is a generator.
This concept itself is very obscure, so if you are a beginner, don’t force yourself to understand it.
Simply put, it is a data generator, or to be more precise, it is an caller-controllable iterator, nothing more.
The Generator function is like a gashapon machine. Every time the user puts in a coin, it spits out a gashapon.
The advantage of this design is that low coupling and controllable.
As for the advanced usage of generator, such as simulating coroutine, you can ignore it for the time being.
Finally, about the design ideas of functions such as map
and filter
.
It can be seen from the characteristics of generator that all it can express is a situation of sequential output, and there is no way to regret it unless you start from scratch.
This is like a factory assembly line, you can only move forward but not backward.
If we have such an assembly line, what can we do?
map
filter
Assembly line production is the embodiment of wisdom in the industrial age. It can maximize execution efficiency, and there is no coupling in each link on the assembly line. Its rationality is quite obvious.
PHPz2017-04-17 13:46:40
This processing is mainly a method of Lazy
evaluation
Imagine some application scenarios where you need to add and sum 10 million Fibonacci numbers.
The second method is a lazy
method, which is the python
idiomatic generator
天蓬老师2017-04-17 13:46:40
I don’t know where the question comes from. The Python2.7 I tested is converted into a for function as follows.
I don’t know if this is also the case in Py3.* (it may have changed)