时间:2021-07-01 10:21:17 帮助过:50人阅读
可被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: '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迭代器的实例详解的详细内容,更多请关注Gxl网其它相关文章!