最后更新于:2020-03-18 10:04:31
python 3.x内置函数next可以从迭代器中检索下一个元素或者数据,可以用于迭代器遍历,使用的时候注意会触发 StopIteration 异常!
语法如下:
next(iterator[,default])
iterator – 迭代器;
default – 可选参数;如果不设置的话,当迭代器没有下一个元素时,会抛StopIteration 异常;如果设置了该参数,没有下一个元素时,默认返回该参数;
返回值:返回迭代器中当前元素的下一个元素;
1.没有设置default参数,使用next函数时,如果没有下一个元素或者数据,会抛StopIteration 异常,注意异常处理;
>>> a = iter('1234')
>>> next(a)
'1'
>>> next(a)
'2'
>>> next(a)
'3'
>>> next(a)
'4'
>>> next(a) # 没有下一个元素的时候使用next,直接抛异常 StopIteration
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
next(a)
StopIteration
2.使用default参数,使用next函数,如果没有下一个元素或者数据,返回default值;
>>> a = iter('1234')
>>> next(a,'e')
'1'
>>> next(a,'e')
'2'
>>> next(a,'e')
'3'
>>> next(a,'e')
'4'
>>> next(a,'e') # 没有下一个元素的时候使用next,直接返回default参数
'e'
>>> next(a,'e')
'e'
转载请注明:猿说Python » python next函数