Python內置函數(44)——next


英文文檔:

next (iterator[, default])
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
說明:
  
  1. 函數必須接收一個可迭代對象參數,每次調用的時候,返回可迭代對象的下一個元素。如果所有元素均已經返回過,則拋出 StopIteration 異常。
>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    next(a)
StopIteration

  2. 函數可以接收一個可選的default參數,傳入default參數后,如果可迭代對象還有元素沒有返回,則依次返回其元素值,如果所有元素已經返回,則返回default指定的默認值而不拋出StopIteration 異常。

>>> a = iter('abcd')
>>> next(a,'e')
'a'
>>> next(a,'e')
'b'
>>> next(a,'e')
'c'
>>> next(a,'e')
'd'
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM