博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python内置函数(36)——iter
阅读量:5181 次
发布时间:2019-06-13

本文共 2343 字,大约阅读时间需要 7 分钟。

英文文档:

iter(object[, sentinel])

Return an object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the method), or it must support the sequence protocol (the method with integer arguments starting at 0). If it does not support either of those protocols, is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its method; if the value returned is equal to sentinel, will be raised, otherwise the value will be returned.

One useful application of the second form of is to read lines of a file until a certain line is reached. The following example reads a file until the method returns an empty string:

with open('mydata.txt') as fp:    for line in iter(fp.readline, ''):        process_line(line)

 

说明:

  1. 函数功能返回一个迭代器对象。

  2. 当第二个参数不提供时,第一个参数必须是一个支持可迭代协议(即实现了__iter__()方法)的集合(字典、集合、不可变集合),或者支持序列协议(即实现了__getitem__()方法,方法接收一个从0开始的整数参数)的序列(元组、列表、字符串),否则将报错。

>>> a = iter({
'A':1,'B':2}) #字典集合>>> a
>>> next(a)'A'>>> next(a)'B'>>> next(a)Traceback (most recent call last): File "
", line 1, in
next(a)StopIteration >>> a = iter('abcd') #字符串序列>>> a
>>> next(a)'a'>>> next(a)'b'>>> next(a)'c'>>> next(a)'d'>>> next(a)Traceback (most recent call last): File "
", line 1, in
next(a)StopIteration

 

  3. 当第二个参数sentinel提供时,第一个参数必须是一个可被调用对象。创建的迭代对象,在调用__next__方法的时候会调用这个可被调用对象,当返回值和sentinel值相等时,将抛出

# 定义类>>> class IterTest:     def __init__(self):        self.start = 0        self.end = 10    def get_next_value(self):        current = self.start        if current < self.end:            self.start += 1        else:            raise StopIteration        return current>>> iterTest = IterTest() #实例化类>>> a = iter(iterTest.get_next_value,4) # iterTest.get_next_value为可调用对象,sentinel值为4>>> a
>>> next(a)0>>> next(a)1>>> next(a)2>>> next(a)3>>> next(a) #迭代到4终止Traceback (most recent call last): File "
", line 1, in
next(a)StopIteration

 

转载于:https://www.cnblogs.com/sesshoumaru/p/6028785.html

你可能感兴趣的文章
layui table 行号
查看>>
C#程序调用外部程序
查看>>
css实现两端对齐~
查看>>
最短路径---Dijkstra/Floyd算法
查看>>
redis可执行文件说明
查看>>
ajax向后台传递数组
查看>>
剑指offer系列14:包含min函数的栈
查看>>
疯狂JAVA16课之对象与内存控制
查看>>
[转载]树、森林和二叉树的转换
查看>>
WPF移动Window窗体(鼠标点击左键移动窗体自定义行为)
查看>>
Java核心技术梳理-类加载机制与反射
查看>>
1593: [Usaco2008 Feb]Hotel 旅馆 (线段树)
查看>>
软件测试-----Graph Coverage作业
查看>>
POJO 与 JavaBean 的区别 !
查看>>
php、mysql查询当天,查询本周,查询本月的数据实例(字段是时间戳)
查看>>
Windows Phone 7手势识别左右滑动 非XNA
查看>>
django ORM创建数据库方法
查看>>
iOS 自定义UIButton(图片和文字混合)
查看>>
Win8下,以管理员身份启动VS项目
查看>>
[bzoj1025][SCOI2009]游戏 (分组背包)
查看>>