首页  >  文章  >  后端开发  >  python迭代器的实例详解

python迭代器的实例详解

零下一度
零下一度原创
2017-06-29 10:06:171948浏览

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

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

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

在使用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 "<stdin>", line 1, in <module>
StopIteration

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

在生产环境中如何判断呢

>>> L = [4,5,6]
>>> I = L.__iter__()
>>> L.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: &#39;list&#39; object has no attribute &#39;__next__&#39;
>>> 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迭代器的实例详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn