在本教程中,我們將借助示例了解 Python next() 函數。
next()
函數從迭代器返回下一項。
示例
marks = [65, 71, 68, 74, 61]
# convert list to iterator
iterator_marks = iter(marks)
# the next element is the first element
marks_1 = next(iterator_marks)
print(marks_1)
# find the next element which is the second element
marks_2 = next(iterator_marks)
print(marks_2)
# Output: 65
# 71
next() 語法
用法:
next(iterator, default)
參數:
- iterator-
next()
從iterator
- default(可選)- 如果迭代器耗盡,則返回此值(沒有下一項)
返回:
next()
函數從迭代器返回下一項。- 如果迭代器已用盡,則返回作為參數傳遞的
default
值。 - 如果省略
default
參數並且iterator
已用盡,則會引發StopIteration
異常。
示例 1:獲取下一項
random = [5, 9, 'cat']
# converting the list to an iterator
random_iterator = iter(random)
print(random_iterator)
# Output: 5
print(next(random_iterator))
# Output: 9
print(next(random_iterator))
# Output: 'cat'
print(next(random_iterator))
# This will raise Error
# iterator is exhausted
print(next(random_iterator))
輸出
<list_iterator object at 0x7feb49032b00> 5 9 cat Traceback (most recent call last): File "python", line 18, in <module> StopIteration
列表是一個可迭代的你可以得到它迭代器通過使用iter()
Python 中的函數。
學習更多關於
我們從上麵程序的最後一條語句中得到一個錯誤,因為我們試圖在沒有下一項可用時獲取下一項(迭代器已用盡)。
在這種情況下,您可以將 default
值作為第二個參數。
示例 2:將默認值傳遞給 next()
random = [5, 9]
# converting the list to an iterator
random_iterator = iter(random)
# Output: 5
print(next(random_iterator, '-1'))
# Output: 9
print(next(random_iterator, '-1'))
# random_iterator is exhausted
# Output: '-1'
print(next(random_iterator, '-1'))
print(next(random_iterator, '-1'))
print(next(random_iterator, '-1'))
輸出
5 9 -1 -1 -1
注意:在內部,next()
調用__next__()
方法。
相關用法
- Python next()用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python numpy.polynomial.hermite.hermmul用法及代碼示例
- Python numpy.seterrobj用法及代碼示例
- Python numpy.tril()用法及代碼示例
- Python numpy.around用法及代碼示例
- Python numpy.random.standard_normal()用法及代碼示例
- Python numpy.select用法及代碼示例
- Python numpy.fft.irfft2用法及代碼示例
- Python numpy.polynomial.hermite_e.hermemul用法及代碼示例
- Python numpy.fft.irfftn用法及代碼示例
- Python numpy.nonzero()用法及代碼示例
- Python numpy.maximum_sctype()用法及代碼示例
- Python numpy.ma.dstack用法及代碼示例
- Python numpy.ma.make_mask_none()用法及代碼示例
- Python numpy.mod用法及代碼示例
- Python numpy.matrix.flatten用法及代碼示例
- Python numpy.ma.MaskedArray.mean用法及代碼示例
- Python numpy.mean()用法及代碼示例
- Python numpy.random.dirichlet用法及代碼示例
注:本文由純淨天空篩選整理自 Python next()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。