在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