在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 11>>> next(o)step 23>>> next(o)step 35>>> next(o)Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。



