1、推导式的方法
创建生成器的方法有很多。第一种方法很简单,只需将列表生成的[]改为()
In [26]: L = [num * 2 for num in range(5)] In [27]: L Out[27]: [0, 2, 4, 6, 8] In [28]: G = (num * 2 for num in range(5)) In [29]: G Out[29]: <generator object <funexpr> at 0x000001D62EA28248>
2、next() 函数
In [30]: next(G) Out[30]: 0 In [31]: next(G) Out[31]: 2 In [32]: next(G) Out[32]: 4 In [33]: next(G) Out[33]: 6 In [34]: next(G) Out[34]: 8 In [35]: next(G) --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-35-b4d1fcb0baf1> in <module> ----> 1 next(G) StopIteration:
3、for循环与list
因为G已经迭代到了ipython测试的最后,所以需要重建G,否则就没有数据了。
In [38]: G = (num * 2 for num in range(5)) In [39]: for i in G: ...: print(i) ...: 0 2 4 6 8 In [40]: list(G) Out[40]: [] In [41]: G = (num * 2 for num in range(5)) In [42]: list(G) Out[42]: [0, 2, 4, 6, 8]
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试