Python内置类型(5)--迭代器类型
指能够被内置函数
next调用并不断返回下一个值,直到最后抛出StopIteration错误表示无法继续返回下一个值的对象称为迭代器(Iterator)
其实以上的说法只是侠义上的迭代器的定义,在python中,迭代器还需要实现可迭代接口(Iterable),可迭代接口需要返回的是一个迭代器对象,这样迭代器就能够被for语句进行迭代。
迭代器对象初步认知
在python中,没有内置迭代器类型的对象,但是可以通过内置函数iter将str、tuple、list、dict、set等类型转换成一个迭代器对象。
>>> s = 'abc'
>>> next(s)
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
next(s)
TypeError: 'str' object is not an iterator
# 以上报错信息可以看出`str`不是迭代器
>>> it_s = iter(s)
>>> next(it_s)
'a'
>>> next(it_s)
'b'
>>> next(it_s)
'c'
>>> next(it_s)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
next(it_s)
StopIteration
# 以上报错信息可以看出`iter(str)`是迭代器
通过不断的调用next(iterator)方法来获取下一个值,这样其实不怎么方便,python提供了更为简洁的方法,即for循环。for循环每执行一次即相当于调用了一次next(iterator)方法,直到捕获到StopIteration异常退出循环。
>>> it_s = iter(s)
>>> for c in it_s:
print(c)
a
b
c
# 以上的例子是使用for循环遍历迭代器
模块collections中的类型Iterator就是迭代器的抽象基类,所有的迭代器都是Iterator的实例。即如果一个对象是Iterator的实例,则说明此对象是迭代器。
from collections import Iterator
>>> isinstance(s,Iterator)
False
>>> isinstance(it_s,Iterator)
True
# 以上信息证实了`str`不是迭代器,而`iter(str)`是迭代器
如何自己实现一个迭代器
根据python鸭子类型的特性,我们自定义的类型中,只要实现了__next()__方法,该方法在每次被调用时不断返回下一个值,直到无法继续返回下一个值时抛出StopIteration异常即可(next(iterator)实际上调用的是iterator内部的__next()__方法)。
定义自己的迭代器
>>> class MyIter():
def __init__(self,max_value):
self.current_value = 0
self.max_value = max_value
def __next__(self):
if self.current_value < self.max_value:
result = self.current_value
self.current_value += 1
return result
else:
raise StopIteration
验证next方法是否不停返回下一个值
>>> my_iter = MyIter(3)
>>> next(my_iter)
0
>>> next(my_iter)
1
>>> next(my_iter)
2
>>> next(my_iter)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
next(my_iter)
StopIteration
验证对象是否可以用于for循环
>>> my_iter = MyIter(3)
>>> for i in my_iter:
print(i)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
for i in my_iter:
TypeError: 'MyIter' object is not iterable
验证对象是否是Iterator实例
>>> from collections import Iterator
>>> isinstance(my_iter,Iterator)
False
从上面的验证可以看出仅仅实现__next()__方法的对象还不是迭代器,真正的迭代器还需要实现一个可迭代接口Iterable。
Iterator和Iterable的关系
在模块collections中的类型Iterator就是迭代器的抽象基类,其实它里面还定义了类型Iterable,它是可迭代对象的抽象基类。先分别通过help命令查看他们的定义:
>>> from collections import Iterator, Iterable
>>> help(Iterator)
Help on class Iterator in module collections.abc:
class Iterator(Iterable)
| Method resolution order:
| Iterator
| Iterable
| builtins.object
|
| Methods defined here:
|
| __iter__(self)
|
| __next__(self)
| Return the next item from the iterator. When exhausted, raise StopIteration
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__(C) from abc.ABCMeta
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__next__'})
>>> help(Iterable)
Help on class Iterable in module collections.abc:
class Iterable(builtins.object)
| Methods defined here:
|
| __iter__(self)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__(C) from abc.ABCMeta
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__iter__'})
通过上面的代码,可以清楚的看出迭代器类型Iterator继承自可迭代类型Iterable,可迭代Iterable继承自object基类,迭代器Iterator类型包含__iter()__和__next()__方法,而可迭代类型Iteratble仅仅包含__iter__()。可迭代对象,通过__iter()__返回一个迭代器对象,迭代器对象的__next()__方法则实际用于被循环。
完善自己实现一个迭代器
我们现在再将MyIter类型实现可迭代接口Iterable,即实现__iter__()方法。
>>> class MyIter():
def __init__(self,max_value):
self.current_value = 0
self.max_value = max_value
def __iter__(self):
return self
def __next__(self):
if self.current_value < self.max_value:
result = self.current_value
self.current_value += 1
return result
else:
raise StopIteration
验证对象是否可以用于for循环
>>> my_iter = MyIter(3)
>>> for i in my_iter:
print(i)
0
1
2
验证对象是否是Iterator实例
>>> from collections import Iterator
>>> isinstance(my_iter,Iterator)
True
总结
- 凡是可作用于
for语句循环的对象都是Iterable可迭代类型。 - 凡是可作用于
next()函数的对象都是Iterator迭代器类型。 str、tuple、list、dict、set等类型是Iterable可迭代类型,但不是Iterator迭代器;通过Iterable可迭代类型的__iter()__方法可以获得一个Iterator迭代器对象,从而使得它们可以被for语句循环。Python的for循环本质上就是通过调用Iterable可迭代对象的__iter()__方法获得一个Iterator迭代器对象,然后不断调用Iterator迭代器对象__next()__方法实现的。
Python内置类型(5)--迭代器类型的更多相关文章
- Python内置类型性能分析
Python内置类型性能分析 timeit模块 timeit模块可以用来测试一小段Python代码的执行速度. class timeit.Timer(stmt='pass', setup='pass' ...
- 为什么继承 Python 内置类型会出问题?!
本文出自"Python为什么"系列,请查看全部文章 不久前,Python猫 给大家推荐了一本书<流畅的Python>(点击可跳转阅读),那篇文章有比较多的"溢 ...
- Python 内置类型 dict, list,线程安全吗
近段时间发现一个 Python 连接数据库的连接是线程不安全的,结果惹得我哪哪儿都怀疑变量的多线程是否安全的问题,今天终于找到了正确答案,那就是 Python 内置类型 dict,list ,tupl ...
- Python——内置类型
Python定义了丰富的数据类型,包括: 数值型:int, float, complex 序列:(iterable) str, unicode, tuple, list, bytearray, buf ...
- 易被忽略的Python内置类型
Python中的内置类型是我们开发中最常见的,很多人都能熟练的使用它们. 然而有一些内置类型确实不那么常见的,或者说往往会被我们忽略,所以这次的主题就是带领大家重新认识这些"不同寻常&quo ...
- python内置类型详细解释
文章编写借鉴于内置类型 - Python 3.7.3 文档,主要用于自己学习和记录 python主要内置类型包括数字.序列.映射.类.实例和异常 有些多项集类是可变的.它们用于添加.移除或重排其成员的 ...
- Python内置类型(6)——生成器
上节内容说到Python的for语句循环本质上就是通过调用Iterable可迭代对象的__iter()__方法获得一个Iterator迭代器对象,然后不断调用Iterator迭代器对象__next() ...
- Python内置类型——set
Python中,内置类型set和frozenset用来表示集合,我们首先查看这两个类型支持的特殊对象,从而可以理解他们的特性. >>> dir(set) ['__and__', '_ ...
- 4、python内置类型(0529)
支持运算:索引,切片,min(), max(), len()等 支持操作:对象的自有的方法 对字符串操作的内置方法获取:str. //敲tab键补全 获取某个内建命令的属性和方法列表:dir( ...
随机推荐
- java爬虫框架webmagic学习(一)
1. 爬虫的分类:分布式和单机 分布式主要就是apache的nutch框架,java实现,依赖hadoop运行,学习难度高,一般只用来做搜索引擎开发. java单机的框架有:webmagic和webc ...
- 转:centos查看实时网络带宽占用情况方法
Linux中查看网卡流量工具有iptraf.iftop以及nethogs等,iftop可以用来监控网卡的实时流量(可以指定网段).反向解析IP.显示端口信息等. centos安装iftop的命令如下: ...
- Moment.js 基本用法
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- vue 自动识别PC、移动端,并跳转到对应页面
app.vuehead中添加 <!--自动识别PC.移动--> <script src="static/js/uaredirect.js" type=" ...
- 如何通过RNA-Seq了解转录本的结构
[转载]如何通过RNA-Seq了解转录本的结构 已有 1942 次阅读 2014-12-26 15:22 |个人分类:转录组测序|系统分类:科研笔记|关键词:RNA-Seq,转录组测序,转录本结构| ...
- Could not transfer artifact org.springframework
无法从中心仓库获取该版本的信息, 从新下载: 1.配置eclipse中的maven user setting路径为本地maven安装路径 配置阿里云镜像路径 <mirror> <i ...
- CSU 1684-Disastrous Downtime
题目链接:https://nanti.jisuanke.com/t/28879 思路:贪心,从最早收到请求的时刻开始,统计每个相差1000毫秒的时间段内接收的请求数量再计算该时间段内所需机器数目,答案 ...
- 11. English vocabulary 英语词汇量
11. English vocabulary 英语词汇量 (1) The exact number of English words is not known.The large dictionari ...
- qhfl-4 注册-登录-认证
认证 任何的项目都需要认证,当用户输入了用户名和密码,验证通过,代表用户登录成功 那HTTP请求是无状态的,下次这个用户再请求,是不可能识别这个用户是否登录的 就要有自己的方式来实现这个认证,用户登录 ...
- Ubuntu 14.04 LTS 下使用源码编译安装 Sagemath 6.7 x64 (小结)
原先博客放弃使用,几篇文章搬运过来 下载源码包 系统的最低要求: 6GB 硬盘 : 2GB RAM. 命令行工具: A C/C++ compiler: Since Sage builds its ow ...