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导入模块 ...
随机推荐
- Java 端口扫描器 TCP的实现方法
想必很多朋友都实现过一个简易的聊天室这个功能,其中涉及到Socket套接字这个类,我们通过一个特定的IP以及特定的端口创建一个服务端的套接字(ServerSocket),以此我们聊天个体的套接字(So ...
- 软工实践 - 第二十八次作业 Beta 冲刺(6/7)
队名:起床一起肝活队 组长博客:https://www.cnblogs.com/dawnduck/p/10146478.html 作业博客:班级博客本次作业的链接 组员情况 组员1(队长):白晨曦 过 ...
- 文件系统之 stat与access
stat命令 stat既有命令也有同名函数,用来获取文件Inode里主要信息,所以stat命令的输出信息比ls命令的输出信息要更详细,stat 跟踪符号链接,lstat不跟踪符号链接,其中会输出对应文 ...
- lintcode-95-验证二叉查找树
95-验证二叉查找树 给定一个二叉树,判断它是否是合法的二叉查找树(BST) 一棵BST定义为: 节点的左子树中的值要严格小于该节点的值. 节点的右子树中的值要严格大于该节点的值. 左右子树也必须是二 ...
- Flink之状态之checkpointing
1.前言 在Flink中,函数和操作符都可以是有状态的.在处理每个消息或者元素时,有状态的函数都会储存信息,使得状态成为精密操作中关键的组成部分. 为了使状态能够容错,Flink会checkpoint ...
- Chrome Extension & Dark Theme
Chrome Extension & Dark Theme https://chrome.google.com/webstore/detail/eimadpbcbfnmbkopoojfekhn ...
- CSS优化压缩
顾名思义缩写有简写意思,那就总结一下CSS缩写知识点.为什么要让CSS属性缩写?1.简化代码.一些CSS属性简写可以减少CSS代码从而减少CSS文件的占用字节.加快网页下载速度和网页加载速度.2.优化 ...
- LeetCode -- Best Time to Buy and Sell Stock系列
Question: Best Time to Buy and Sell Stock Say you have an array for which the ith element is the pri ...
- underscore的bind和bindAll方法
bind方法和bindAll方法都是用来设定函数的this值的,区别是调用方式不同. var xiaoming = { say:function(){ console.log('I am xiaomi ...
- angular响应式编程
1.响应式编程 例子import {Observable} from "rxjs/Observable"; Observable.from([1,2,3,4]) .filter(( ...