【说站】python生成器创建的方法整理
2023-06-13 09:13:17 时间
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生成器创建的方法整理,希望对大家有所帮助。
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
相关文章
- python详细安装教程环境配置_Python配置环境
- python中矩阵的转置怎么写_Python 矩阵转置的几种方法小结
- python读写、创建文件、文件夹等等
- python 生成数组_Python创建数组「建议收藏」
- python开发中重写父类的方法有哪些?
- Python的使用方法「建议收藏」
- 2.海龟作图—-用Python绘图[通俗易懂]
- python最好的开发工具_Python编译器
- 【说站】python创建平衡二叉树的方法
- python的re模块分组匹配
- 上手python之序列
- 如何在 Python 中创建静态类数据和静态类方法?
- Python 自动化指南(繁琐工作自动化)第二版:一、PYTHON 基础知识
- Linux创建Python文件的步骤(linux新建python文件)
- 使用Python编程连接MySQL数据库(python连mysql)
- Linux查看Python版本的有效方法(linux查看python版本)
- Linux查看Python安装路径的方法(linux查看python安装路径)
- 在Linux系统中使用Python编程语言(linux中python)
- Python与MySQL实现数据分析的完美组合(mysql中python)
- 如何在 i5 上实现 20 倍的 Python 运行速度?
- Python随机生成中文验证码的实例代码
- Python下singleton模式的实现方法
- Python生成pdf文件的方法