Python內建函數(36)——iter,python內建36iter

來源:互聯網
上載者:User

Python內建函數(36)——iter,python內建36iter

英文文檔:

iter(object[, sentinel])

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:    for line in iter(fp.readline, ''):        process_line(line)

 

說明:

  1. 函數功能返回一個可迭代對象。

  2. 當第二個參數不提供時,第一個參數必須是一個支援可迭代協議(即實現了__iter__()方法)的集合(字典、集合、不可變集合),或者支援序列協議(即實現了__getitem__()方法,方法接收一個從0開始的整數參數)的序列(元組、列表、字串),否則將報錯。

>>> a = iter({'A':1,'B':2}) #字典集合>>> a<dict_keyiterator object at 0x03FB8A50>>>> next(a)'A'>>> next(a)'B'>>> next(a)Traceback (most recent call last):  File "<pyshell#36>", line 1, in <module>    next(a)StopIteration >>> a = iter('abcd') #字串序列>>> a<str_iterator object at 0x03FB4FB0>>>> next(a)'a'>>> next(a)'b'>>> next(a)'c'>>> next(a)'d'>>> next(a)Traceback (most recent call last):  File "<pyshell#29>", line 1, in <module>    next(a)StopIteration

 

  3. 當第二個參數sentinel提供時,第一個參數必須是一個可被調用對象。建立的迭代對象,在調用__next__方法的時候會調用這個可被調用對象,當傳回值和sentinel值相等時,將拋出StopIteration異常, 終止迭代。

# 定義類>>> class IterTest:     def __init__(self):        self.start = 0        self.end = 10    def get_next_value(self):        current = self.start        if current < self.end:            self.start += 1        else:            raise StopIteration        return current>>> iterTest = IterTest() #執行個體化類>>> a = iter(iterTest.get_next_value,4) # iterTest.get_next_value為可調用對象,sentinel值為4>>> a<callable_iterator object at 0x03078D30>>>> next(a)0>>> next(a)1>>> next(a)2>>> next(a)3>>> next(a) #迭代到4終止Traceback (most recent call last):  File "<pyshell#22>", line 1, in <module>    next(a)StopIteration

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.