当前位置: 首页 > 编程日记 > 正文

理解Python的迭代器(转)

原文地址: http://python.jobbole.com/81916/

另外一篇文章: http://www.cnblogs.com/kaituorensheng/p/3826911.html

什么是迭代

可以直接作用于for循环的对象统称为可迭代对象(Iterable)。

可以被next()函数调用并不断返回下一个值的对象称为迭代器(Iterator)。

所有的Iterable均可以通过内置函数iter()来转变为Iterator。

对迭代器来讲,有一个__next()__就够了。在你使用for 和 in 语句时,程序就会自动调用即将被处理的对象的迭代器对象,然后使用它的__next__()方法,直到监测到一个StopIteration异常。

>>> L = [1,2,3]
>>> [x**2 for x in L]
[1, 4, 9]
>>> next(L)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: 'list' object is not an iterator
>>> I=iter(L)
>>> next(I)
1
>>> next(I)
2
>>> next(I)
3
>>> next(I)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
StopIteration

上面例子中,列表L可以被for进行循环但是不能被内置函数next()用来查找下一个值,所以L是Iterable。

L通过iter进行包装后设为I,I可以被next()用来查找下一个值,所以I是Iterator。

题外话:

内置函数iter()仅仅是调用了对象的__iter()__方法,所以list对象内部一定存在方法__iter__()
内置函数next()仅仅是调用了对象的__next()__方法,所以list对象内部一定不存在方法__next__(),但是Itrator中一定存在这个方法。
for循环内部事实上就是先调用iter()把Iterable变成Iterator在进行循环迭代的。

>>> L = [4,5,6]
>>> I = L.__iter__()
>>> L.__next__()
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__next__'
>>> I.__next__()
4
>>> from collections import Iterator, Iterable
>>> isinstance(L, Iterable)
True
>>> isinstance(L, Iterator)
False
>>> isinstance(I, Iterable)
True
>>> isinstance(I, Iterator)
True
>>> [x**2 for x in I]    
[25, 36]

Iterator继承自Iterable,从下面的测试中可以很方便的看到Iterator包含__iter()__和next()方法,而Iteratble仅仅包含__iter__()。

>>> from collections import Iterator, Iterable
>>> help(Iterator)
Help on class Iterator:class Iterator(Iterable)Method resolution order:IteratorIterablebuiltins.object   **注解:从这里可以看出Iterable继承自object, Iterator继承自Iterable。Methods defined here:__iter__(self)__next__(self)Return the next item from the iterator. When exhausted, raise StopIteration
......
>>> help(Iterable)
Help on class Iterable:class Iterable(builtins.object)Methods defined here:__iter__(self)

iterable需要包含有__iter()__方法用来返回iterator,而iterator需要包含有__next__()方法用来被循环

如果我们自己定义迭代器,只要在类里面定义一个 iter() 函数,用它来返回一个带 next() 方法的对象就够了。

直接上代码

class Iterable:def __iter__(self):return Iterator()class Iterator:def __init__(self):self.start=-1def __next__(self):self.start +=2if self.start >10:raise StopIterationreturn self.startI = Iterable()
for i in I:print(i)

上面的代码实现的是找到10以内的奇数,代码中的类名可以随便取,不是一定需要使用我上面提供的类名的。

如果在Iterator的__next__方法中没有实现StopIteration异常,那么则是表示的全部奇数,那么需要在调用的时候设置退出循环的条件。

class Iterable:def __iter__(self):return Iterator()class Iterator:def __init__(self):self.start=-1def __next__(self):self.start +=2return self.startI = Iterable()
for count, i in zip(range(5),I):    #也可以用内置函数enumerate来实现计数工作。print(i)

我们通过range来实现打印多少个元素,这里表示打印5个元素,返回结果和上面一致。

当然,我们可以把这两个类合并在一起,这样实现程序的简练。
最终版本如下

class Iterable:def __iter__(self):return selfdef __init__(self):self.start=-1def __next__(self):self.start +=2if self.start >10:raise StopIterationreturn self.startI = Iterable()
for i in I:print(i)

复制迭代器

迭代器是一次性消耗品,使用完了以后就空了,请看。

>>> L=[1,2,3]
>>> I=iter(L)
>>> for i in I:
...     print(i, end='-')
...
1-2-3-
>>>next(I)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
StopIteration

当循环以后就殆尽了,再次使用调用时会引发StopIteration异常。

我们想通过直接赋值的形式把迭代器保存起来,可以下次使用。
但是通过下面的范例可以看出来,根本不管用。

>>> I=iter(L)
>>> J=I
>>> next(I)
1
>>> next(J)
2
>>> next(I)
3
>>> next(J)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
StopIteration

那怎么样才能达到我们要的效果呢?

我们需要使用copy包中的deepcopy了,请看下面:

>>> import copy
>>> I=iter(L)
>>> J=copy.deepcopy(I)
>>> next(I)
1
>>> next(I)
2
>>> next(J)
1

迭代器不能向后移动, 不能回到开始。

所以需要做一些特殊的事情才能实现向后移动等功能。

以上代码均在Python 3.4 中测试通过。

转载于:https://www.cnblogs.com/nyist-xsk/p/7404897.html

相关文章:

快捷导航动画制作

做了一个仿大众点评的快捷导航动画效果&#xff0c;点击导航内的箭头&#xff0c;导航缩放&#xff0c;点击快捷导航再伸展。 看效果图&#xff1a; 实现代码&#xff1a; <block wx:if"{{!isCustom}}"><view class"home_and_reSource" animati…

instant apps_Android Instant Apps 101:它们是什么以及它们如何工作

instant appsby Tomislav Smrečki通过TomislavSmrečki Android Instant Apps are a cool new way to consume native apps without prior installation. Only parts of the app are downloaded and launched, giving the users a native look and feel in a couple of secon…

数据库分享一: MySQL的Innodb缓存相关优化

无论是对于哪一种数据库来说&#xff0c;缓存技术都是提高数据库性能的关键技术&#xff0c;物理磁盘的访问速度永 远都会与内存的访问速度永远都不是一个数量级的。通过缓存技术无论是在读还是写方面都可以大大提 高数据库整体性能。Innodb_buffer_pool_size 的合理设置Innodb…

用过美德乐吸奶器的宝妈们感觉比国产吸奶器怎么样啊?

药效好不好&#xff0c;看疗效就知道。吸奶器好不好看评价就知道。我们来看看美德乐吸奶器 天猫旗舰店 : http://medela.wang 的宝妈们的评价如可 拔奶神器&#xff0c;绝对好过贝亲&#xff01;最初一次七八十&#xff0c;后来一百多&#xff0c;现在可以翻个倍。结合宝宝吮吸…

小程序地图多个 circles 使用demo

效果图&#xff1a; 代码&#xff1a; var that; const app getApp() const util require("../../utils/util.js") const data require("../../utils/map.js") Page({data: {pageShow: false,scale: 15,obj: {},longitude: 116.34665554470486,latitud…

编写文档_如何通过编写优质文档来使自己的未来快乐

编写文档by Gabriele Cimato加布里埃莱西马托(Gabriele Cimato) 如何通过编写优质文档来使自己的未来快乐 (How to make your future self happy by writing good docs) 或者&#xff0c;在清除旧代码库时如何减少痛苦 (Or how to be less miserable when dusting off an old …

(转载)人人都会OSGI--实例讲解OSGI开发

http://longdick.iteye.com/blog/457310转载于:https://www.cnblogs.com/eecs2016/articles/7422310.html

小程序json字符串转 json对象 { name :你好} 转成 { name :你好}

解决后端接口返回 var obj "{ name :"你好"}" 类似这样的数据&#xff0c;对象或者数组外面包了一层引号&#xff0c; 把这种数据转成 var obj { name :"你好"}&#xff1b; 直接上代码&#xff1a; // pages/test/test.js Page({jsonStrToJ…

每天写的叫工作日志,每周写的总结叫周报,每月写的叫月报

有些时候&#xff0c;老板会突发让您求每天都要写工作周报&#xff0c;什么项目什么任务&#xff0c;完成情况&#xff0c;完成花费的时间等&#xff0c;然后汇总部门周报&#xff1b;也不是写不出&#xff0c;只是不知道有时候重复做一个项目&#xff0c;到底每天有什么好写&a…

为什么分散刷新没有死时间_分散项目为何失败(以及如何处理)

为什么分散刷新没有死时间The most exciting thing about working in the decentralized economy is the fact that no one has any idea as to where it’ll all end up!在去中心decentralized economy工作最令人振奋的事情是&#xff0c;没有人知道最终的结果&#xff01; T…

.NET Core 常用加密和Hash工具NETCore.Encrypt

前言 在日常开发过程中&#xff0c;不可避免的涉及到数据加密解密&#xff08;Hash&#xff09;操作&#xff0c;所以就有想法开发通用工具&#xff0c;NETCore.Encrypt就诞生了。目前NETCore.Encrypt只支持.NET Core ,工具包含了AES,DES,RSA加密解密&#xff0c;MD5&#xff0…

url 通配符解析成参数

需求&#xff1a;url 参数是通配符&#xff0c;需要把通配符解析成参数并且拼接到 url 中 例如&#xff1a;https://xxx.cn/index.html$a1$b2; 解析成 https://xxx.cn/index.html?a1&b2; 时间关系&#xff0c;直接上代码&#xff0c;有时间再补上注释 下面是小程序页…

性能测试分享:系统架构

性能测试分享&#xff1a;系统架构 转载于:https://www.cnblogs.com/poptest/p/4904584.html

graphql是什么_为什么GraphQL是避免技术债务的关键

graphql是什么GraphQL (not to be confused with GraphDB or Open Graph or even an actual graph) is a remarkably creative solution to a relatively common problem: How do you enable front end developers to access backend data in exactly the way they need it?Gr…

JS如何判断json是否为空

1、判断json是否为空 jQuery.isEmptyObject()&#xff1b; 2、遍历json function getHsonLength(json{var jsonLength0;for (var i in json){jsonLength;}return jsonLength;}转载于:https://www.cnblogs.com/donaldworld/p/7423811.html

微软算法100题11 求二叉树中两节点之间的最大距离

第11 题求二叉树中节点的最大距离...如果我们把二叉树看成一个图&#xff0c;父子节点之间的连线看成是双向的&#xff0c;我们姑且定义"距离"为两节点之间边的个数。写一个程序&#xff0c;求一棵二叉树中相距最远的两个节点之间的距离 思路: 一棵树中节点的最大距…

小程序订阅消息 订阅消息开发

微信小程序交流QQ群&#xff1a; 173683895 173683866 526474645 。 群内打广告或者脏话一律飞机票 订阅消息 当用户勾选了订阅面板中的“总是保持以上选择&#xff0c;不再询问”时&#xff0c;模板消息会被添加到用户的小程序设置页&#xff0c;通过 wx.getSetting…

meetup_如何使用标准库和Node.js构建Meetup Slack机器人

meetupby Janeth Ledezma简妮丝莱德兹玛(Janeth Ledezma) 如何使用标准库和Node.js构建Meetup Slack机器人 (How to build a Meetup Slack bot with Standard Library and Node.js) In this guide, you will learn how to set up a Slack application that will display infor…

.NET使用OpenSSL生成的pem密钥文件[1024位]

using System; using System.Text; using System.Security.Cryptography; using System.Web; using System.IO;namespace Thinhunan.Cnblogs.Com.RSAUtility {public class PemConverter{/// <summary>/// 将pem格式公钥转换为RSAParameters/// </summary>/// <…

[2014百度之星资格赛]

第一个问题&#xff1a; Energy Conversion Problem Description魔法师百小度也有遇到难题的时候——如今。百小度正在一个古老的石门面前&#xff0c;石门上有一段古老的魔法文字&#xff0c;读懂这样的魔法文字须要耗费大量的能量和大量的脑力。过了许久。百小度最终读懂魔法…

视频录制,压缩实现源码

实现代码&#xff1a; <!DOCTYPE html> <html><head><meta charset"utf-8"><title></title><meta name"viewport" content"widthdevice-width, initial-scale1.0"><!-- <script src"./js…

alexa技能个数_如何在您的技能中使用Alexa演示语言

alexa技能个数by Garrett Vargas通过Garrett Vargas 如何在您的技能中使用Alexa演示语言 (How to use Alexa Presentation Language in your skill) Amazon recently released the Alexa Presentation Language (APL). APL provides a richer display for multimodal skills. …

HTML与XML总结

阅览《孙欣HTML》和《刘炜XML》过了一段时间&#xff0c;在这里学到的内容用思维导图来概括。HTML与XML都是标记语言。 同样点&#xff1a; HTML文档与XML文档有类似的结构。前者是&#xff08;head和body&#xff09;后者是&#xff08;声明和主体&#xff09;&#xff0c;大致…

ant PageHeaderWrapper 返回上一页

PageHeaderWrapper 返回上一页实现代码&#xff1a; <PageHeaderWrappertitle{false}content{<a onClick{() > router.goBack()}><Icon type"left" />返回</a>}breadcrumb{{routes: [{ path: /, breadcrumbName: 首页 },{ path: /pay_orde…

ruby 新建对象_Ruby面向对象编程的简介

ruby 新建对象by Saul Costa由Saul Costa Object-oriented programming (OOP) is a programming paradigm organized around objects. At a high level, OOP is all about being able to structure code so that its functionality can be shared throughout the application.…

ASP.NET导出文件FileResult的使用

本文给大家讲一下ASP.NET MVC中如何使用FileResult来导出文件&#xff0c;首先网上相关例子有很多大神都有讲&#xff0c;我在这只是稍微说一点不同——为什么我的导出没有反应呢&#xff1f; 这个问题&#xff0c;我找了半天也没有找到&#xff0c;最后是在一个网友的评论中体…

【AHOI 2016初中组】 自行车比赛 - 贪心

题目描述 小雪非常关注自行车比赛&#xff0c;尤其是环滨湖自行车赛。一年一度的环滨湖自行车赛&#xff0c;需要选手们连续比赛数日&#xff0c;最终按照累计得分决出冠军。今年一共有 N 位参赛选手。每一天的比赛总会决出当日的排名&#xff0c;第一名的选手会获得 N 点得分&…

【Ant Design Pro 三】样式动态绑定 react样式绑定

第一步&#xff0c;创建样式文件&#xff0c;在页面目录下根据自己习惯创建一个less文件&#xff0c;用来写样式类 第二部&#xff0c;引用该文件 import styles from ./details.less; //details.less 代码&#xff1a; .menu {width: 95%; } .navigation-menu{width: 90%; …

react hooks使用_如何使用React和Hooks检测外部点击

react hooks使用by Andrei Cacio通过安德烈卡西奥(Andrei Cacio) 如何使用React和Hooks检测外部点击 (How to detect an outside click with React and Hooks) “外部点击”是什么意思&#xff1f; (What does “Outside Click” mean?) You can think of it as the “anti-b…

正则表达式(1)

正则表达式的概念 正则表达式是一个字符串&#xff0c;使用单个字符串来描述、用来定义匹配规则&#xff0c;匹配一系列符合某个句法规则的字符串。在开发中&#xff0c;正则表达式通常被用来检索、替换那些符合某个规则的文本。 正则表达式的匹配规则 字符类&#xff1a;[abc]…