失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python迭代器的实例详解

python迭代器的实例详解

时间:2020-05-18 04:13:42

相关推荐

python迭代器的实例详解

后端开发|Python教程

python,迭代

后端开发-Python教程

可直接作用于for循环的对象叫做可迭代对象(iterable);

精品源码免费分享,vscode 对比git,ubuntu的开始菜单打不开,tomcat. dns,sqlite按日期查询,js流程路插件,前端h5框架an,爬虫如何设置代理ip,php sql 过滤,校园seo优势,免费网站计数器代码,html上传网页模板,下载网站模板如何编辑软件lzw

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

比特币源码,ubuntu中的软件,野草爬虫子图片,xgettext php,46seolzw

所有的可迭代对象均可以通过内置函数iter()来转变为迭代器。

微擎 高考成绩单源码,ubuntu上运行c,爬虫下载官网,php与web页面交互设计代码,瞒总seolzw

在使用for循环的时候,程序就会自动调用即将处理的对象的迭代器对象,然后使用它的next()方法,直到检测一个stoplteration异常。

>>> l = [4,5,6,7,8,9,0] #这是一个列表>>> i = iter(l) #可迭代对象转换为迭代器;>>> next(i)4>>> next(i)5>>> next(i)6>>> next(i)7>>> next(i)8>>> next(i)9>>> next(i)0>>> next(i)Traceback (most recent call last): File "", line 1, in StopIteration

因为列表中么有超过0的数字,所以当范围超过的话,就会返回一个StopIteration异常。

在生产环境中如何判断呢

>>> L = [4,5,6]>>> I = L.__iter__()>>> L.__next__()Traceback (most recent call last): File "", line 1, in 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]

如果觉得《python迭代器的实例详解》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。