iter和next

iter

iter(...)
    iter(collection) -> iterator
    iter(callable, sentinel) -> iterator
    
    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.

如果是传递两个参数给 iter() , 第一个参数必须是callable ,它会重复地调用第一个参数, 
直到迭代器的下个值等于sentinel:即在之后的迭代之中,迭代出来sentinel就立马停止。

 class IT(object):
        def __init__(self):
               self.l=[1,2,3,4,5]
               self.i=iter(self.l)
        def __call__(self):   #定义了__call__方法的类的实例是可调用的
               item=next(self.i)
               print "__call__ is called,which would return",item
               return item
        def __iter__(self): #支持迭代协议(即定义有__iter__()函数)
               print "__iter__ is called!!"
               return iter(self.l)

>>> it=IT() #it是可调用的
>>> it1=iter(it,3) #it必须是callable的,否则无法返回callable_iterator
>>> callable(it)
True
>>> it1
<callable-iterator object at 0x0306DD90>
>>> for i in it1:
print i

__call__ is called,which would return 1
1
__call__ is called,which would return 2
2
__call__ is called,which would return 3

可以看到传入两个参数得到的it1的类型是一个callable_iterator,它每次在调用的时候,都会调用__call__函数,并且最后输出3就停止了。
>>> it2=iter(it)
__iter__ is called!!
>>> it2
<listiterator object at 0x030A1FD0>
>>> for i in it2:
print i,


1 2 3 4 5

next():返回迭代器下一个元素,通过调用next()方法实现(python3中__next__)。如果default参数有设置,当下一个元素不存在时,就返回default参数的值,否则抛出异常StopIteration。

参考资料:http://blog.csdn.net/sxingming/article/details/51479039

    http://blog.csdn.net/caimouse/article/details/43235363

原文地址:https://www.cnblogs.com/songbird/p/7524852.html