python模块学习:Iterators和Generators
转自:http://www.cnblogs.com/zhbzz2007/p/6102695.html
1 迭代器:
迭代器,允许你在一个容器上进行迭代的对象。
python的迭代器主要是通过__iter__和__next__两个方法来实现。
__iter__,要求你的容器支持迭代,返回对象本身。如果想创建一个迭代器对象,还需要实现__next__方法,这个返回下一个对象。
为了对这些概念更加清晰,让我们回顾下面的两个定义:
- 可迭代对象(iterable),只定义了__iter__方法;
- 迭代器(iterator),定义了__iter__和__next__两个方法,__iter__返回迭代器本身,__next__方法返回下一个元素
所有函数名中有双下划线的方法,都很神奇,你不需要直接调用__iter__或者__next__。你可以使用for循环或者转换为列表,Python就会自动替你调用这些方法。当然你或许还是想调用它们,那么你可以使用Python内置的函数iter和next方法。
python3中,list是支持迭代的,但不是迭代器对象。因为,它不支持__next__
看代码:
a=[1,2,3,4,5]
next(a)
错误信息是:
C:\Python35\python.exe C:/Users/wcf/PycharmProjects/Algorithms/wcf.py
Traceback (most recent call last):
File "C:/Users/wcf/PycharmProjects/Algorithms/wcf.py", line 3, in <module>
next(a)
TypeError: 'list' object is not an iterator Process finished with exit code 1
通过iter内建函数,可以把他转变成迭代器:
a=[1,2,3,4,5] for item in iter(a):
print(item)
当你使用循环来遍历一个迭代器,你就不需要调用next方法,你也无需担心会收到StopIteration异常信息。
比如:
a=[1,2,3,4,5] a_iter=iter(a)
next(a_iter)
next(a_iter)
next(a_iter)
next(a_iter)
next(a_iter)
next(a_iter)
next(a_iter)
会出错的:
C:\Python35\python.exe C:/Users/wcf/PycharmProjects/Algorithms/wcf.py
Traceback (most recent call last):
File "C:/Users/wcf/PycharmProjects/Algorithms/wcf.py", line 10, in <module>
next(a_iter)
StopIteration Process finished with exit code 1
2.创建属于自己的迭代器,很简单,实现几个方法就可以:
class my_iterator():
def __init__(self,letters):
self.letters=letters
self.position=0 def __iter__(self):
return self def __next__(self):
if self.position>=len(self.letters):
raise StopIteration
letter=self.letters[self.position]
self.position+=1
return letter if __name__=="__main__":
i=my_iterator('abcd')
for item in i:
print(item)
3.生成器
一个普通的Python函数经常返回一个值,无论它是列表、整数还是其他对象。但是如果你想调用一个函数,这个函数能否产生一系列值呢?这个就是生成器诞生的原因。生成器的工作机制是保存它所停止(或者说它已经产生)的位置,然后给主调函数返回一个值。不是返回一个调用函数的执行,生成器仅仅返回一个临时的控制返回。为了完成这个功能,生成器函数需要使用Python的 yield 语句。
def double_generator():
number=2
while True:
yield number
number+=2 doubler =double_generator() print(next(doubler))
print(next(doubler))
print(next(doubler))
print(next(doubler))
输出是:
C:\Python35\python.exe C:/Users/wcf/PycharmProjects/Algorithms/wcf.py
2
4
6
8 Process finished with exit code 0
实际上,上文,也有一个next方法。
而下面的例子,就是没有:
def double_generator():
yield 'wcf1'
yield 'wcf2'
yield 'wcf3' doubler =double_generator() print(next(doubler))
print(next(doubler))
print(next(doubler))
输出是:
C:\Python35\python.exe C:/Users/wcf/PycharmProjects/Algorithms/wcf.py
wcf1
wcf2
wcf3 Process finished with exit code 0
同样的,如果是:
def double_generator():
yield 'wcf1'
yield 'wcf2'
yield 'wcf3' doubler =double_generator() print(next(doubler))
print(next(doubler))
print(next(doubler))
print(next(doubler))
一样会触发一场:
C:\Python35\python.exe C:/Users/wcf/PycharmProjects/Algorithms/wcf.py
wcf1
Traceback (most recent call last):
wcf2
wcf3
File "C:/Users/wcf/PycharmProjects/Algorithms/wcf.py", line 12, in <module>
print(next(doubler))
StopIteration Process finished with exit code 1
而这样写,就ok:
def double_generator():
yield 'wcf1'
yield 'wcf2'
yield 'wcf3' doubler =double_generator() for item in doubler:
print(item)
python模块学习:Iterators和Generators的更多相关文章
- 【转】Python模块学习 - fnmatch & glob
[转]Python模块学习 - fnmatch & glob 介绍 fnmatch 和 glob 模块都是用来做字符串匹配文件名的标准库. fnmatch模块 大部分情况下使用字符串匹配查找特 ...
- 【目录】Python模块学习系列
目录:Python模块学习笔记 1.Python模块学习 - Paramiko - 主机管理 2.Python模块学习 - Fileinput - 读取文件 3.Python模块学习 - Confi ...
- Python模块学习filecmp文件比较
Python模块学习filecmp文件比较 filecmp模块用于比较文件及文件夹的内容,它是一个轻量级的工具,使用非常简单.python标准库还提供了difflib模块用于比较文件的内容.关于dif ...
- python模块学习第 0000 题
将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果. 类似于图中效果: 好可爱>%<! 题目来源:https://github.com/Yixiao ...
- Python模块学习:logging 日志记录
原文出处: DarkBull 许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net ...
- 解惑Python模块学习,该如何着手操作...
Python模块 晚上和朋友聊天,说到公司要求精兵计划,全员都要有编程能力.然后C.Java.Python-对于零基础入门的,当然是选择Python的人较多了.可朋友说他只是看了简单的语法,可pyth ...
- Python模块学习
6. Modules If you quit from the Python interpreter and enter it again, the definitions you have made ...
- Python模块学习系列
python模块-time python模块-datetime python模块-OS模块详解
- Python模块学习遇到的问题
Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案 Python使用import导入模块 ...
随机推荐
- BufferedInputStream/BufferedOutputStream
BufferedInputStream: public synchronized int read() throws IOException int res=bis.read(); System.ou ...
- [热键冲突]MacOS下 Pycharm的全局搜索Ctrl+Shift+F失灵
刚换了MacOS 发现Pycharm下的全局搜索Ctrl+Shift+F失灵了, 经过帖子 https://blog.csdn.net/pxinm/article/details/64444560 知 ...
- neutron DVR
DVR 简介 DVR 提出的背景 在 Neutron 的网络环境中,跨子网的虚机通信是需要通过 Neutron 的路由器.这既包括不同子网的虚拟机之间的通信,又包括虚拟机与外网之间的通信.在 DVR ...
- PAT 甲级 1006 Sign In and Sign Out
https://pintia.cn/problem-sets/994805342720868352/problems/994805516654460928 At the beginning of ev ...
- Cache的封装和使用
ICache 接口 using System; using System.Collections.Generic; using System.Linq; using System.Text; usin ...
- QT启动一个工程
功能描述: 模拟如下页面. 当输入一个字符串时打开对应的应用程序. 实现方法: 1. 建立工程 2. 界面编辑: 3. 在test1.h中添加slot声明 4. test1.cpp中添加slot定义 ...
- 安装与配置JDK
第一步:下载jdk-7-linux-i586.tar.gzwget -c http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-i586. ...
- 数据结构—队列(Queue)
队列的定义--Queue 队列是只允许在表的队尾插入,在表的队头进行删除.队列具有先进先出的特性(FIFO, First In First Out). 队列提供了下面的操作 q.empty() 如果队 ...
- 【NOIP模拟赛】就 反悔贪心
biubiu~~~ 这道题,考场上上来就dp然后发现怎么优化也不行.............最后发现是贪心............. 正解:带反悔的贪心,原理是,假设我们现在得到了取i个的最优解那么我 ...
- 你知道HTML标签设计的本意吗?
“DIV+CSS”这个词汇不知道害了多少人,也许其提出者本意并没有错,但是跟风者从表现曲解了其意思,认为整个页面就应当是DIV+CSS文件的组合.这样做,对于视觉上并没有什么影响,因为还原了之前设计的 ...