• Python 迭代器


    1、迭代器定义

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

      next      返回容器的下一个项目

      __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:	estiter.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
  • 相关阅读:
    三连击
    铺地毯
    超级玛丽游戏
    A+B problem
    怎么感觉欠缺点什么、灵光在哪,让我顿悟下
    2016年10月,人生的转折点。
    python第七天
    python第六天
    汉诺塔问题(Hanoi Tower)递归算法解析(Python实现)
    计算多数的乘积(Python实现)
  • 原文地址:https://www.cnblogs.com/alvin2010/p/9310142.html
Copyright © 2020-2023  润新知