Python next()方法

Python next()函数 返回迭代器的下一项。在本文中,我们将介绍 next()语法,next()参数,next()返回。

null

语法: 下一步(国际热核实验堆,stopdef)

参数:

  • 国际热核实验堆: 要在其上执行迭代的迭代器。
  • stopdef: 到达迭代器末尾时打印的默认值。

返回: 返回列表中的下一个元素,如果不存在,则打印默认值。如果默认值不存在,则引发StopIteration错误。

Python next()方法示例

例1: 演示next()的工作原理

在这里,我们将看到循环中的python next()。

Python3

# Python code to demonstrate
# working of next()
# initializing list
list1 = [ 1 , 2 , 3 , 4 , 5 ]
# converting list to iterator
list1 = iter (list1)
print ( "The contents of list are : " )
# printing using next()
# using default
while ( 1 ):
val = next (list1, 'end' )
if val = = 'end' :
print ( 'list end' )
break
else :
print (val)


输出:

The contents of list are : 12345list end

示例2:从迭代器中获取下一项

Python3

list1 = [ 1 , 2 , 3 , 4 , 5 ]
# converting list to iterator
list1 = iter (list1)
print (list1)
print ( next (list1))
print ( next (list1))
print ( next (list1))


输出:

<list_iterator object at 0x0000021D7C801D88>123

示例3:将默认值传递给next()

Python3

list1 = [ 1 , 2 , 3 , 4 , 5 ]
# converting list to iterator
list1 = iter (list1)
print (list1)
print ( next (list1, - 1 ))
print ( next (list1, - 1 ))
print ( next (list1, - 1 ))
print ( next (list1, - 1 ))
print ( next (list1, - 1 ))
print ( next (list1, - 1 ))
print ( next (list1, - 1 ))


输出:

<list_iterator object at 0x0000021D7AE08908>12345-1-1

示例6:Python next()停止迭代

Python3

list1 = [ 1 , 2 , 3 , 4 , 5 ]
# converting list to iterator
list1 = iter (list1)
print (list1)
print ( next (list1))
print ( next (list1))
print ( next (list1))
print ( next (list1))
print ( next (list1))
print ( next (list1))


输出:

<list_iterator object at 0x0000021D7ADF55C8>12345---------------------------------------------------------------------------StopIteration                             Traceback (most recent call last)<ipython-input-17-02f0e1df3bbe> in <module>    10 print(next(list1))    11 print(next(list1))---> 12 print(next(list1))StopIteration: 

当调用超出迭代器范围时,会出现StopProtection错误,为了避免此错误,我们将使用默认值作为参数。

例5: 性能分析

Python3

# Python code to demonstrate
# next() vs for loop
import time
# initializing list
list1 = [ 1 , 2 , 3 , 4 , 5 ]
# keeping list2
list2 = list1
# converting list to iterator
list1 = iter (list1)
print ( "The contents of list are : " )
# printing using next()
# using default
start_next = time.time()
while ( 1 ):
val = next (list1, 'end' )
if val = = 'end' :
break
else :
print (val)
print ( "Time taken for next() is : " + str (time.time() - start_next))
# printing using for loop
start_for = time.time()
for i in list2:
print (i)
print ( "Time taken for loop is : " + str (time.time() - start_for))


输出:

The contents of list are : 12345Time taken for next() is : 5.96046447754e-0612345Time taken for loop is : 1.90734863281e-06

结果:Python下一个For循环 在打印列表内容时,是比next()更好的选择。

应用: next()是用于打印iter类型容器组件的实用函数。它的用法是当容器的大小未知时,或者当列表/迭代器耗尽时,我们需要给出提示。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享