鱼C论坛

 找回密码
 立即注册
查看: 2091|回复: 1

[技术交流] Python next() 函数

[复制链接]
发表于 2020-3-21 12:17:45 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 一个账号 于 2020-3-21 12:21 编辑

Python next() 函数


语法

  1. next(iterator[, default])
复制代码


参数

参数描述
iterator迭代器
default当没有下一个元素时返回该默认值。


描述

next() 函数用于获取迭代器的下一项。如果没设置 default 参数,又没有下一项元素则会触发 StopIteration 异常。

返回值

返回迭代器的下一项。

例子

  1. >>> next([1, 2, 3])   # 必须是迭代器
  2. Traceback (most recent call last):
  3.   File "<pyshell#0>", line 1, in <module>
  4.     next([1, 2, 3])
  5. TypeError: 'list' object is not an iterator
  6. >>> iterator = iter([1, 2, 3, 4])
  7. >>> next(iterator)
  8. 1
  9. >>> next(iterator)
  10. 2
  11. >>> next(iterator)
  12. 3
  13. >>> next(iterator)
  14. 4
  15. >>> next(iterator)   # 没有下一个元素了
  16. Traceback (most recent call last):
  17.   File "<pyshell#8>", line 1, in <module>
  18.     next(iterator)
  19. StopIteration
  20. >>> next(iterator, "没有下一个元素了!")
  21. '没有下一个元素了!'
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-10 03:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表