- 在Python中,这种一边循环一边计算的机制,称为生成器:generator。
创建生成器方法(1)
- 要创建一个生成器,有很多种方法。第一种方法很简单,只要把一个列表生成式的 [ ] 改成 ( )
可以用next(list)打印出来
In [18]: l = [x for x in range(10)]
In [19]: l
Out[19]: [0, 1, 2, 3, 4,5,6,7,8,9]
In [20]: l = (x for x in range(10))
In [21]: l
Out[21]: <generator object <genexpr> at 0x7f92fadaed58>
In [22]: next(l)
Out[22]: 0
In [23]: next(l)
Out[23]: 1
In [24]: next(l)
Out[24]: 2
In [25]: next(l)
Out[25]: 3
In [26]: next(l)
Out[26]: 4
In [27]: next(l)
Out[28]: 5
In [29]: next(l)
Out[30]: 6
In [31]: next(l)
Out[32]: 7
In [33]: next(l)
Out[34]: 8
In [35]: next(l)
Out[36]: 9
In [37]: next(l)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-37-101c36968c6d> in <module>()
----> 1 next(l)
- 生成器的应用
-
下面是程序运行的结果
e.PNG
网友评论