每天学点Python之Iterator

x33g5p2x  于2021-03-13 发布在 Python  
字(1.0k)|赞(0)|评价(0)|浏览(609)

我们经常需要遍历一个对象中的元素,在Python中这种功能是通过迭代器来实现的。

原理

每一个迭代器可以通过反复调用迭代器的__next__()方法来返回创建该迭代器的对象中的后继值。当没有可用数据时,产生一个StopInteration异常。此时,迭代器对象被耗尽,之后再调用 next()方法只会再次产生StopInteration异常。需要访问的对象要求包含一个__iter__()方法,用于返回迭代器对象,如果对象就实现了迭代器方法,就可以返回对象本身。

使用

我们可以通过调用iter()方法来返回对象的迭代器:

  1. >>> i = iter("hello")
  2. >>> i.__next__()
  3. 'h'
  4. >>> next(i)
  5. 'e'
  6. >>> next(i)
  7. 'l'
  8. >>> next(i)
  9. 'l'
  10. >>> next(i)
  11. 'o'
  12. >>> next(i)
  13. Traceback (most recent call last):
  14. File "<input>", line 1, in <module>
  15. StopIteration

对于Python中常见的一些数据类型,如元组、列表、字典等都已经自己实现了迭代器功能,这使得它们能在for循环中正常工作:

  1. >>> for i in (2,3,1):
  2. ... print(i)
  3. ...
  4. 2
  5. 3
  6. 1

自定义

如果我们要求自定义访问对象中的数据,那该如何做呢,我们需要实现__iter()__和__next()__方法,下面我们给出自己的对象,实现一个简易的计时器功能:

  1. class CountDown:
  2. def __init__(self, start):
  3. self.count = start
  4. def __iter__(self):
  5. return self
  6. def __next__(self):
  7. if self.count <= 0:
  8. raise StopIteration
  9. r = self.count
  10. self.count -= 1
  11. return r
  12. if __name__ == "__main__":
  13. for time in CountDown(3):
  14. print(time)
  15. 输出:3 2 1

相关文章