python内置函数next通过调用对象的__next__方法从迭代器中取值,当迭代器耗尽又没有为next函数设置default默认值参数,使用next函数将引发StopIteration异常。
源码解析:
def next(iterator, default=None): # real signature unknown; restored from __doc__
"""
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""
pass
python中next()的具体的形式为:next(iterobject,defalt)
- 第一个参数是可迭代的对象
- 第二个参数可以写也可以不写,不写的时候,如果可迭代的元素取出完毕,会返回StopIteration异常,第二个参数写的时候,当可迭代对象迭代完后,会返回第二个参数写的那个元素。
示例代码1:
str_list = []
for i in range(5):
str_num = 'num' + str(i+1)
str_list.append(str_num)
print(str_list)
# 只传第一个参数
it = iter(str_list)
for _ in range(8):
res = next(it)
print(res)
运行结果:
示例代码2:
str_list = []
for i in range(5):
str_num = 'num' + str(i+1)
str_list.append(str_num)
print(str_list)
# 传两个参数
it = iter(str_list)
for _ in range(8):
# res = next(it, -1)
res = next(it, '-1')
print(res)
运行结果: