您的位置:首页 > 编程语言 > Python开发

Python中iter函数用法简述

2016-07-10 18:53 645 查看
Python 中关于iter(object[, sentinel)]方法有两个参数。

使用iter(object)这种形式比较常见。

iter(object, sentinel)这种形式一般较少使用,Python的文档说明貌似也不容易理解。

1,iter(object)

Python官方文档对于这种形式的解释很容易理解。

此时,object必须是集合对象,且支持迭代协议(iteration protocol)或者支持序列协议(sequence protocol)。

说白了,也就是实现了iter()方法或者getitem()方法。

lst = [1, 2, 3]
for i in iter(lst):
print(i)


2,iter(object, sentinel)

Python官方文档对于这种形式的解释是:“ 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.”。

这句话的意思是说:如果传递了第二个参数,则object必须是一个可调用的对象(如,函数)。此时,iter创建了一个迭代器对象,每次调用这个迭代器对象的next()方法时,都会调用object。

如果next的返回值等于sentinel,则抛出StopIteration异常,否则返回下一个值。

class counter:

def __init__(self, _start, _end):
self.start = _start
self.end = _end

def get_next(self):
s = self.start
if(self.start < self.end):
self.start += 1
else:
raise StopIteration

return s

c = counter(1, 5)
iterator = iter(c.get_next, 3)
print(type(iterator))
for i in iterator:
print(i)


执行结果:

<class 'callable_iterator'>
1
2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 python iter