python高级特性-生成器

在python中一边循环一边计算的机制成为生成器(generator)

在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

生成list

>>> L=[x*x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

生成generator

>>> G=(x*x for x in range(10))
>>> G
<generator object <genexpr> at 0x7f5cc1ce3c80>

两者的区别就在于最外层的[]和(),L是一个list,而g是一个generator

yield生成器

>>> def odd():
... print('step 1')
... yield 1
... print('step 2')
... yield(3)
... print('step 3')
... yield(5)
...

>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
原文地址:https://www.cnblogs.com/yaohong/p/7484602.html