开发者社区> 问答> 正文

python必备内置函数- iter(object, sentinel)

python必备内置函数- iter(object, sentinel)

展开
收起
请回答1024 2020-03-30 11:35:03 543 0
1 条回答
写回答
取消 提交回答
  • 返回一个可迭代对象, 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

    2020-03-30 11:35:56
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载