一尘不染

Python-生成器理解到底如何工作?

python

生成器理解是做什么的?它是如何工作的?


阅读 345

收藏
2020-02-20

共1个答案

一尘不染

生成器表达式就像一个列表推导,但是它没有找到你感兴趣的所有项目并将它们打包到列表中,而是等待,并逐个生成表达式中的每个项目。

>>> my_list = [1, 3, 5, 9, 2, 6]
>>> filtered_list = [item for item in my_list if item > 3]
>>> print(filtered_list)
[5, 9, 6]
>>> len(filtered_list)
3
>>> # compare to generator expression
... 
>>> filtered_gen = (item for item in my_list if item > 3)
>>> print(filtered_gen)  # notice it's a generator object
<generator object <genexpr> at 0x7f2ad75f89e0>
>>> len(filtered_gen) # So technically, it has no length
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'generator' has no len()
>>> # We extract each item out individually. We'll do it manually first.
... 
>>> next(filtered_gen)
5
>>> next(filtered_gen)
9
>>> next(filtered_gen)
6
>>> next(filtered_gen) # Should be all out of items and give an error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> # Yup, the generator is spent. No values for you!
... 
>>> # Let's prove it gives the same results as our list comprehension
... 
>>> filtered_gen = (item for item in my_list if item > 3)
>>> gen_to_list = list(filtered_gen)
>>> print(gen_to_list)
[5, 9, 6]
>>> filtered_list == gen_to_list
True
>>> 

由于生成器表达式一次只需要产生一项,因此可以节省大量内存。在需要一次获取一项,根据该项进行大量计算然后移至下一项的情况下,生成器表达式最有意义。如果需要多个值,则还可以使用生成器表达式,一次获取几个。如果在程序继续执行之前需要所有值,请改用列表推导。

2020-02-20