Python 迭代器

匿名 (未验证) 提交于 2019-12-02 22:56:40

1、迭代器定义

  迭代器只不过是一个实现了迭代器协议的容器对象。它基于两个方法:

  __iter__  返回迭代器本身

2、内建函数iter()

  迭代器可以通过内置函数iter()和一个序列创建:

it = iter(abc) print it.next() print it.next() print it.next() print it.next()
a b c Traceback (most recent call last):   File "f:\test\iter.py", line 7, in <module>     print it.next() StopIteration

  当序列遍历完时,将抛出StopIteration异常,这使迭代器和循环兼容,因为它们将捕获这个异常而停止循环。

3、生成定制迭代器

  要创建定制迭代器,编写一个具有next()方法的类,只要该类提供返回迭代器实例的__iter__()方法即可。

class MyIterator(object):      def __init__(self, step):         self.step = step      def next(self):         if self.step == 0:             raise StopIteration         self.step -= 1          return self.step      def __iter__(self):         return self   for it in MyIterator(4):     print it
3 2 1 0

原文:https://www.cnblogs.com/alvin2010/p/9310142.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!