zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    会跳舞的树(只用HTML+CSS)(转)
    国内UED收录
    HDU 1078 dfs+dp
    HDU 1278
    HDU 4499
    HDU 4597
    POJ2777
    POJ1780 Code
    简单的Fleury算法模板
    POJ 2513 无向欧拉通路+字典树+并查集
  • 原文地址:https://www.cnblogs.com/alvin2010/p/9310142.html
Copyright © 2011-2022 走看看