zoukankan      html  css  js  c++  java
  • Python随心记--迭代器协议和for循环机制

    迭代器协议:
    对象必须提供一个next方法,执行该方法要命返回迭代中下一项,要么就引起一个Stoplteration异常,以终止迭代(只能往后走不能往前退)
    可迭代对象:
    实现了迭代器协议的对象(如何实现:对象内部定义一个__iter__()方法)
    协议是一种约定,可迭代对象实现了迭代器协议,pythond额内部工具(如for循环,sum、min、max函数)使用迭代器协议访问对象
    x = 'hello'
    iter_test = x.__iter__()
    print(iter_test)
    print(iter_test.__next__())
    print(iter_test.__next__())
    print(iter_test.__next__())
    print(iter_test.__next__())
    print(iter_test.__next__())

    for循环基于迭代器协议先执行x.__iter__(),跟索引没有半毛钱关系
    x = [1,2,3,4]
    print(x[0])
    iter_x = x.__iter__()
    print(iter_x.__next__())
    x = [1,2,3,4]
    #列表的遍历
    index = 0
    while index < len(x):
        print(x[index])
        index += 1
    x = {1,2,3,4}
    for i in x:
        print(i)
    #for循环的执行原理如下 -_-
    iter_x = x.__iter__()
    print(iter_x.__next__())
    模拟fon循环  try.....except StopIteration  捕捉异常
    x = {1,2,3,4}
    diedai_x = x.__iter__()
    while True:
        try:
            print(diedai_x.__next__())
        except StopIteration:
            print('迭代完毕,循环终止')
            break
    生成器
      yield #生成器定义关键字
    def test():
        yield 1
        yield 2
        yield 3
    g = test()   #得到生成器表达式
    print(g)
    
    
  • 相关阅读:
    单div绘制多元素图
    js笔试题系列之二——数组与对象
    JS设计模式——策略模式
    js笔试题系列之三——函数
    zepto.js中的Touch事件
    java定时任务之Scheduled注解
    汤姆大叔送书,咱也科学抢书
    Asp.net Mvc自定义客户端验证(CheckBox列表的验证)
    摆脱烂项目
    我的ORM发展史
  • 原文地址:https://www.cnblogs.com/Essaycode/p/10105280.html
Copyright © 2011-2022 走看看