Python内置函数 next的具体使用方法,python内置函数next
Python内置函数 next的具体使用方法,python内置函数next
Python 3中的File对象不支持next()方法。 Python 3有一个内置函数next(),它通过调用其next ()方法从迭代器中检索下一个项目。 如果给定了默认值,则在迭代器耗尽返回此默认值,否则会引发StopIteration。 该方法可用于从文件对象读取下一个输入行。
语法
以下是next()方法的语法 -
next(iterator[,default])
参数
- iterator − 要读取行的文件对象
- default − 如果迭代器耗尽则返回此默认值。 如果没有给出此默认值,则抛出 StopIteration 异常
返回值
此方法返回下一个输入行
英文文档:
next(iterator[, default])
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
说明:
1. 函数必须接收一个可迭代对象参数,每次调用的时候,返回可迭代对象的下一个元素。如果所有元素均已经返回过,则抛出StopIteration 异常。
>>> a = iter('abcd') >>> next(a) 'a' >>> next(a) 'b' >>> next(a) 'c' >>> next(a) 'd' >>> next(a) Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> next(a) StopIteration
2. 函数可以接收一个可选的default参数,传入default参数后,如果可迭代对象还有元素没有返回,则依次返回其元素值,如果所有元素已经返回,则返回default指定的默认值而不抛出StopIteration 异常。
>>> a = iter('abcd') >>> next(a,'e') 'a' >>> next(a,'e') 'b' >>> next(a,'e') 'c' >>> next(a,'e') 'd' >>> next(a,'e') 'e' >>> next(a,'e') 'e'
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持帮客之家。
相关内容
- Python实现矩阵转置的方法分析,python实现矩阵
- 详解python上传文件和字符到PHP服务器,
- Python二叉树的定义及常用遍历算法分析,python二叉树
- Python实现列表删除重复元素的三种常用方法分析,pyt
- python多进程实现进程间通信实例,python实例
- python之virtualenv的简单使用方法(必看篇),pythonvirtualen
- 分享一个简单的python读写文件脚本,
- python自动裁剪图像代码分享,python裁剪图像
- python shell根据ip获取主机名代码示例,python主机名
- 深入理解Python中range和xrange的区别,pythonxrange
评论关闭