python 迭代器

要理解python迭代器(iterator),先要理解两个概念:Iterable(可迭代对象)Iterator(迭代器)

先来help()一下Iterator

>>> 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

发现,Iterator是继承自Iterable,迭代器必须实现__iter__()__next__()

再来看看Iterable:

>>> help(Iterable)
Help on class Iterable in module collections.abc: class Iterable(builtins.object)
| Methods defined here:
|
| __iter__(self)
|

Iterable只定义了__iter__()

现在来说说__iter__()__next__()的作用

1、__iter__() 返回一个迭代器对象

2、__next__()返回迭代器对象的下一个item,如果没有更多的item则raise一个StopIteration异常

来做一个实验

>>> from collections import Iterator, Iterable
>>> l = list('hello world')
>>> isinstance(l, Iterator)
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'isinstace' is not defined
>>> isinstance(l, Iterable)
True

从上面的执行结果可以看出,list 对象 l 是 Iterable 而不是 Iterator

>>> next(l)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'list' object is not an iterator
>>> iter_l = iter(l)
>>> for i in range(len(l)+1):
... next(iter_l)
...
'h'
'e'
'l'
'l'
'o'
' '
'w'
'o'
'r'
'l'
'd'
Traceback (most recent call last):
File "<input>", line 2, in <module>
StopIteration

next() 只接受 iterator 作为参数,不接受 iterable。要想用 next() 对 l 进行迭代,要先执行 iter(l) 将 l 转为 iterator

Python3 学习笔记------迭代器的更多相关文章

  1. Python3学习笔记--迭代器

    迭代 使用一个循环来遍历某个东西时这个过程本身叫做迭代. 可迭代对象 python中只要定义了可以返回一个迭代器的__iter__方法,或者定义了可以支持下标索引的__getitem__方法,那么它就 ...

  2. python3学习笔记(6)_iteration

    #python3 学习笔记17/07/10 # !/usr/bin/env python3 # -*- coding:utf-8 -*- #类似 其他语言的for循环,但是比for抽象程度更高 # f ...

  3. Python3学习笔记(urllib模块的使用)转http://www.cnblogs.com/Lands-ljk/p/5447127.html

    Python3学习笔记(urllib模块的使用)   1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None,  ...

  4. Python3学习笔记 - 准备环境

    前言 最近乘着项目不忙想赶一波时髦学习一下Python3.由于正好学习了Docker,并深深迷上了Docker,所以必须趁热打铁的用它来创建我们的Python3的开发测试环境.Python3的中文教程 ...

  5. python3学习笔记(7)_listComprehensions-列表生成式

    #python3 学习笔记17/07/11 # !/usr/bin/env python3 # -*- conding:utf-8 -*- #通过列表生成式可以生成格式各样的list,这种list 一 ...

  6. python3学习笔记(5)_slice

    #python3 学习笔记17/07/10 # !/usr/bin/env python3 # -*- coding:utf-8 -*- #切片slice 大大简化 对于指定索引的操作 fruits ...

  7. 《Head first设计模式》学习笔记 – 迭代器模式

    <Head first设计模式>学习笔记 – 迭代器模式 代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示. 爆炸性新闻:对象村餐厅和对象村煎饼屋合并了!真是个 ...

  8. python3学习笔记10(迭代器和生成器)

    参考http://www.runoob.com/python3/python3-iterator-generator.html 迭代器 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束 ...

  9. Python3学习笔记01-环境安装和运行环境

    最近在学习Python3,想写一些自己的学习笔记.方便自己以后看,主要学习的资料来自菜鸟教程的Python3教程和廖雪峰官方网站的Python教程. 1.下载 1)打开https://www.pyth ...

随机推荐

  1. Mininet在创建拓扑的过程中为什么不打印信息了——了解Mininet的log系统

    前言 写这篇博客是为了给我的愚蠢和浪费的6个小时买单! 过程原因分析 我用Mininet创建过不少拓扑了,这次创建的拓扑非常简单,如下图,创建拓扑的代码见github.在以前的拓扑创建过程中,我都是用 ...

  2. SNMP 原理与实战详解

    原文地址:http://freeloda.blog.51cto.com/2033581/1306743 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法 ...

  3. RabbitMQ官方中文入门教程(PHP版) 第三部分:发布/订阅(Publish/Subscribe)

    发布/订阅 在上篇教程中,我们搭建了一个工作队列.每个任务之分发给一个工作者(worker).在本篇教程中,我们要做的之前完全不一样——分发一个消息给多个消费者(consumers).这种模式被称为“ ...

  4. Linux下解决用户不能执行sudo的方法

    报错: xxx is not in the sudoers file.  This incident will be reported. Linux默认没有为当前用户开启sudo权限! $ su  $ ...

  5. Spring 配置文件中将common.properties文件外置

    将配置文件的路径从项目中移出来 1. 在springApplicationContext中 <context:property-placeholder location="file:$ ...

  6. 【POJ 2187】Beauty Contest 凸包+旋转卡壳

    xuán zhuǎn qiǎ ké模板题 是这么读吧(≖ ‿ ≖)✧ 算法挺简单:找对踵点即可,顺便更新答案. #include<cstdio> #include<cstring&g ...

  7. Mybatis 自动生成代码

    准备条件: 将下面的文件放入同一目录下 操作步骤: 1/ 在 generatorConfig.xml 中配置相关的参数,与需要被自动生成的表 也可以 执行项目中的MybatisConfigAutoGe ...

  8. 网页提示[Not allowed to load local resource: file://XXXX]错误

    网页通过http 访问时, 点击打开文件的link.在Chrome 中会报 Not allowed to load local resource: file// XXXX 的错误 <!--Add ...

  9. 动画: ThemeTransition(过渡效果)

    介绍背水一战 Windows 10 之 动画 ThemeTransition 的概述 EntranceThemeTransition - 页面间跳转时的过渡效果 ContentThemeTransit ...

  10. 让webstorm支持avalon语法自动补全

    在file菜单下选择Settings,选择Editor ——> Inspections ——> Html ——> Unknown HTML tag attibute添加以下标签ms- ...