|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 一个账号 于 2020-3-21 12:21 编辑
Python next() 函数
语法
- next(iterator[, default])
复制代码
参数
参数 | 描述 | iterator | 迭代器 | default | 当没有下一个元素时返回该默认值。 |
描述
next() 函数用于获取迭代器的下一项。如果没设置 default 参数,又没有下一项元素则会触发 StopIteration 异常。
返回值
返回迭代器的下一项。
例子
- >>> next([1, 2, 3]) # 必须是迭代器
- Traceback (most recent call last):
- File "<pyshell#0>", line 1, in <module>
- next([1, 2, 3])
- TypeError: 'list' object is not an iterator
- >>> iterator = iter([1, 2, 3, 4])
- >>> next(iterator)
- 1
- >>> next(iterator)
- 2
- >>> next(iterator)
- 3
- >>> next(iterator)
- 4
- >>> next(iterator) # 没有下一个元素了
- Traceback (most recent call last):
- File "<pyshell#8>", line 1, in <module>
- next(iterator)
- StopIteration
- >>> next(iterator, "没有下一个元素了!")
- '没有下一个元素了!'
复制代码 |
|