您的位置:

44. Python next()

Python next()

更新:

内置函数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