內置函數next()
用於從迭代器返回下一個元素。通常該函數用在循環中。當它到達迭代器的末尾時,它會拋出一個錯誤。為了避免這種情況,我們可以指定默認值。
**next(iterator, default)** #where iterable can be list, tuple etc
下一個()參數:
接受兩個參數。在這種情況下,迭代器可以是字元串、位元組、元組、列表或範圍,集合可以是字典、集合或凍結集合。
參數 | 描述 | 必需/可選 |
---|---|---|
可迭代的 | 從迭代器中檢索到下一項 | 需要 |
系統默認值 | 如果迭代器用盡,則返回該值 | 可選擇的 |
下一個()返回值
如果它到達迭代器的末尾,並且沒有指定默認值,它將引發 StopIteration 異常。
| 投入 | 返回值 |
| 迭代程序 | 迭代器的下一個元素 |
Python 中next()
方法的示例
示例 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 at="" object="">5
9
cat
Traceback (most recent call last):
File "python", line 18, in <module>StopIteration</module></list_iterator>
示例 2:將默認值傳遞給下一個()
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
示例 3:函數到達集合末尾時拋出一個錯誤
# Python `next()` function example
number = iter([256, 32, 82]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
# fourth item
item = next(number) # error, no item is present
print(item)
輸出:
Traceback (most recent call last):
File "source_file.py", line 14, in
item = next(number)
StopIteration
256
32
82
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/246186.html