您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python内置函 iter

2024/6/27 8:25:51发布32次查看
英文文档:
iter(object[, sentinel])
return an iterator 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 __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). if it does not support either of those protocols, typeerror 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__next__() method; if the value returned is equal to sentinel, stopiteration will be raised, otherwise the value will be returned.
one useful application of the second form of iter() is to read lines of a file until a certain line is reached. the following example reads a file until the readline() 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值相等时,将抛出stopiteration异常, 终止迭代。
# 定义类 >>> class itertest: def __init__(self): self.start = 0 self.end = 10 def get_next_value(self): current = self.start if current >> itertest = itertest() #实例化类 >>> a = iter(itertest.get_next_value,4) # itertest.get_next_value为可调用对象,sentinel值为4 >>> a >>> next(a) >>> next(a) >>> next(a) >>> next(a) >>> next(a) #迭代到4终止 traceback (most recent call last): file , line 1, in next(a) stopiteration
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product