當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python next方法用法及代碼示例

Python 的 next(~) 方法返回迭代器中的下一項。

參數

1. iterator | iterator

我們應該返回下一個項目的迭代器。

2. default | any | optional

當我們到達迭代器末尾時要返回的值。

返回值

返回值取決於以下情況:

案子

返回值

尚未耗盡迭代器中的所有項目

迭代器中的下一項

已用盡迭代器和提供的 default 參數中的所有項目

default

已用盡迭代器中的所有項目,並且未提供 default 參數

StopIteration

錯誤

例子

基本用法

要獲取迭代器中的下一項test

a = ['hi', 'bye', 'see you']
# converting the list to an iterator called test
test = iter(a)
print(next(test))
print(next(test))
print(next(test))



hi
bye
see you

請注意,每次調用 next(~) 方法時,我們都會返回迭代器 test 中的下一項。

默認參數

指定 'This is the default value' 的默認值:

b = ['hi', 'bye', 'see you']
# converting the list to an iterator called test
test = iter(b)
print(next(test, 'This is the default value'))
print(next(test, 'This is the default value'))
print(next(test, 'This is the default value'))
print(next(test, 'This is the default value'))



hi
bye
see you
This is the default value

在第四次調用 next(~) 方法時,我們返回 'This is the default value',因為我們已經耗盡了迭代器 test 中的所有項目。

StopIteration錯誤

如果我們不提供 default 值並且到達迭代器的末尾:

c = ['hi', 'bye', 'see you']
# converting the list to an iterator called test
test = iter(c)
print(next(test))
print(next(test))
print(next(test))
print(next(test))



hi
bye
see you
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-11-74eba8c03080> in <module>
      7 print(next(test))
      8 print(next(test))
----> 9 print(next(test))
StopIteration:

我們看到,由於迭代器 test 中沒有更多項,因此引發了 StopIteration 異常。

相關用法


注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 Python | next method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。