【说站】python生成器创建的方法整理
python生成器创建的方法整理
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生成器创建的方法整理,希望对大家有所帮助。更多编程基础知识学习:python学习网
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
本站发布的内容若侵犯到您的权益,请邮件联系站长删除,我们将及时处理!
从您进入本站开始,已表示您已同意接受本站【免责声明】中的一切条款!
本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行研究。
本站资源仅供学习和交流使用,版权归原作者所有,请勿商业运营、违法使用和传播!请在下载后24小时之内自觉删除。
若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,使用者自行承担,概与本站无关。