鱼C论坛

 找回密码
 立即注册
查看: 1674|回复: 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
回复

使用道具 举报

发表于 2020-3-25 09:29:50 | 显示全部楼层
本帖最后由 永恒的蓝色梦想 于 2020-4-10 18:27 编辑

一种可能的实现

  1. def next(iterator,default=_no_arg,/):
  2.     if hasattr(iterator,'__next__') and callable(iterator.__next__):
  3.         if default is _no_arg:
  4.             return iterator.__next__()

  5.         try:
  6.             return iterator.__next__()

  7.         except StopIteration:
  8.             return default

  9.     else:
  10.         raise TypeError(f"'{iterator.__class__.__name__}' object is not an iterator")
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-19 23:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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