- 在Python中,這種一邊循環(huán)一邊計算的機制,稱為生成器:generator请祖。
創(chuàng)建生成器方法(1)
- 要創(chuàng)建一個生成器,有很多種方法脖祈。第一種方法很簡單肆捕,只要把一個列表生成式的 [ ] 改成 ( )
可以用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)