- 在Python中轧拄,這種一邊循環(huán)一邊計(jì)算的機(jī)制,稱為生成器:generator讽膏。
創(chuàng)建生成器方法(1)
- 要?jiǎng)?chuàng)建一個(gè)生成器檩电,有很多種方法。第一種方法很簡(jiǎn)單府树,只要把一個(gè)列表生成式的 [ ] 改成 ( )
可以用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)
- 生成器的應(yīng)用
-
下面是程序運(yùn)行的結(jié)果