iter和next

iterpython

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。spa

 

參考資料:http://blog.csdn.net/sxingming/article/details/51479039.net

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

相關文章
相關標籤/搜索