内置函数 next() 用于从迭代器中返回下一个元素。此函数通常在循环中使用。当它到达迭代器末尾时,会抛出错误,为了避免这种情况,我们可以指定默认值。
next(iterator, default) #where iterable can be list, tuple etc
接受两个参数。其中,迭代器可以是字符串、字节、元组、列表或范围,集合可以是字典、集合或不可变集合。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 可迭代对象 | 从迭代器中检索下一个项目 | 必需 |
| 默认值 | 如果迭代器耗尽,则返回此值 | 可选 |
如果它到达迭代器末尾且未指定默认值,它将引发 StopIteration 异常。
| 输入 | 返回值 |
|---|---|
| 迭代器 | 迭代器中的下一个元素 |
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))
输出
5 9 cat Traceback (most recent call last): File "python", line 18, in StopIteration
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
# 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