Python內建函數 next的具體使用方法,python內建函數next

來源:互聯網
上載者:User

Python內建函數 next的具體使用方法,python內建函數next

Python 3中的File對象不支援next()方法。 Python 3有一個內建函數next(),它通過調用其next ()方法從迭代器中檢索下一個項目。 如果給定了預設值,則在迭代器耗盡返回此預設值,否則會引發StopIteration。 該方法可用於從檔案對象讀取下一個輸入行。

文法

以下是next()方法的文法 -

next(iterator[,default])

參數

  1. iterator − 要讀取行的檔案對象
  2. default − 如果迭代器耗盡則返回此預設值。 如果沒有給出此預設值,則拋出 StopIteration 異常

傳回值

此方法返回下一個輸入行

英文文檔:

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'

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.