可以用 for 和 while 循环来调用生成器, 取里面的值.
比如 a=(i for i in range (10)
- for i in a:
- print(i)
输出为:
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- while True:
- print(next(a)
输出为:
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- Traceback (most recent call last):
- File "F:/python/2019.6.2/xuexi/6.2 / 列表生成器. py", line 21, in <module>
- print(next(a))
- StopIteration
所以用 for 循环, 执行完后不会报错, while 会报错.
python3 里的 range 其实就是一个生成器.
来源: http://www.bubuko.com/infodetail-3109500.html