python必备内置函数- iter(object, sentinel)
返回一个可迭代对象, sentinel可省略
In [72]: lst = [1,3,5]
In [73]: for i in iter(lst):
...: print(i)
...:
1
3
5
sentinel 理解为迭代对象的哨兵,一旦迭代到此元素,立即终止:
In [81]: class TestIter(object): ...: def init(self): ...: self.l=[1,3,2,3,4,5] ...: self.i=iter(self.l) ...: def call(self): #定义了__call__方法的类的实例是可调用的 ...: item = next(self.i) ...: print ("call is called,which would return",item) ...: return item ...: def iter(self): #支持迭代协议(即定义有__iter__()函数) ...: print ("iter is called!!") ...: return iter(self.l) ...:
In [82]: t = TestIter() ...: t1 = iter(t, 3) ...: for i in t1: ...: print(i) ...: call is called,which would return 1 1 call is called,which would return 3
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。