python中的iterator介绍及应用场景

来源:互联网 发布:数据分析相关岗位 编辑:程序博客网 时间:2024/06/01 07:24

        迭代器作为PY编程中比较常见的一个概念,也经常被我们所提及。然而若想深入到其内部了解其来龙去脉却也一时难以搞懂,恰巧群里面一个兄弟提及了这样一个问题,特来深入了解一下,并和大家分享出来。(注意:我本人一直在Version2.7上游离,所以若非特别注明,所有相关博客内容都是建立在这个版本上的)

原文及理解

New in version 2.2.
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always supportthe iteration methods.
(从版本2.2开始,python就支持利用容器来实现迭代的功能,是利用两个方法来实现的。这两个方法是为了让用户自定义的class能支持迭代.......)


The iterator objects themselves are required to support the following twomethods, which together form the iterator protocol:
iterator.__iter__()
      Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
iterator.next()
      Return the next item from the container. If  there are no further items, raise the StopIteration exception. This method corresponds to thetp_iternext slot of the type structure for Python objects in thePython/C API.

(可迭代对象必须包含如下两个源自迭代协议中要求的方法:__iter__()和next()。__iter__()返回的是可迭代对象本身,这样就可以使此对象在for...in...语句中使用。另外,这个方法对应Python/C API中的......;而next()方法则返回容器的下一个item,若没有下一个item的话,就会引发StopIteration异常......)


举例

            应用场景:在一个包含有列表对象的容器对象上执行迭代操作

我们自定义一个类方法来获得一个等比数列,并分别定义出__iter__()和next()方法。按照上面的说法,我们需要在__iter__()中返回类本身,即“return self”,在next()方法中,我们定义每一个要返回的item,即“前一个数乘2后返回”。

#!usr/bin/env python# -*- coding:utf-8 -*-class MyIterator(object):    """Show a iterator example which shows all items less than 100 and greater than 2in a geometric progression.        a user-defined CLASS inheriteded from type object        Args:            x: a default integer:2, defines the begging parameter            xmax:a default integer:100, defines the ending parameter        Returns:            obviously, it could have been an iterator object as expected.        Raise:            An error occurred while no further iterator items    """    def __init__(self, x=2, xmax=100):        self.__mul,self.__x = x,x        self.__xmax = xmax            def __iter__(self):        '''return the iterator object itself'''        return self        def next(self):        if self.__x and self.__x != 1:            self.__mul = self.__mul * self.__x            if self.__mul <= self.__xmax:                return self.__mul            else:                raise StopIteration        else:            raise StopIteration        if __name__ == "__main__":    m_iter = MyIterator()    #for more invisiable of an iterator, we use print derectly instead    #for itm in m_iter:    #    print itm    print next(m_iter)    print next(m_iter)    print next(m_iter)    print next(m_iter)    print next(m_iter)

运行结果:

48163264


注意

  • iterator是一个消耗型的容器,上面的示例中,‘64’是最后一个数字,如果我们再第六次调用next()方法,则会引发StopIteration异常,感兴趣的自己试一下。
  • 在python3.X中,上述next()不再奏效,需要换成__next__()才行;同样,在python2.7中__next__()也是不奏效的,具体情况大家自行试验。
0 0
原创粉丝点击