python内置函数next()方法用法详解
  TEZNKK3IfmPf 2023年11月13日 23 0

        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)

运行结果:

python内置函数next()方法用法详解

示例代码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)

运行结果:

python内置函数next()方法用法详解

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年04月19日   18   0   0 python
  TEZNKK3IfmPf   2024年04月19日   25   0   0 idepython
TEZNKK3IfmPf