📜  Python next()函数

📅  最后修改于: 2020-10-30 05:35:35             🧑  作者: Mango

Python next()函数

Python next()函数用于从集合中获取下一个项目。它带有两个参数:迭代器和默认值,并返回一个元素。

此方法调用迭代器,如果不存在任何项目,则引发错误。为了避免错误,我们可以设置一个默认值。

该函数的签名在下面给出。

签名

next (iterator[, default])

参量

迭代器:它是一个迭代器对象。

默认值:如果元素不存在,则返回此值。

返回

它从集合中返回一个项目。

让我们看一些next()函数的示例,以了解其功能。

Python next()函数示例1

在这里,我们使用next()函数获取项目。它不需要任何循环或索引。

# 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)

输出:

256
32
82

Python next()函数示例2

到达集合末尾时,此函数将引发错误。请参见下面的示例。

# 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

Python next()函数示例3

# Python next() function example
number = iter([256, "javatpoint", 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, "No item is present") # error, no item is present
print(item)

输出:

256
javatpoint
82
No item is present

Python next()函数示例4

在这里,我们设置一个默认值。现在,它不会引发任何错误,而是返回默认值。

# Python next() function example
number = iter([256, "javatpoint", 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, "No item is left") # no error due to default value
print(item)

输出:

256
javatpoint
82
No item is left