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]
以上就是python生成器创建的方法整理,希望对大家有所帮助。更多编程基础知识学习:
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。