zoukankan      html  css  js  c++  java
  • Python yield解析

      Pyhton generators and the yield keyword 

      At a glance,the yield statement is used to define generators,repalcing the return of a function to provide a result to its caller without destorying local variables.Unlike a function,where on each call it starts with new set of variables,a generator will resume the execution where it was left off.

      被yield修饰的函数,会被python解释器当作generator

      示例代码:

    def countdown():
        i=5
        while i>0:
            yield i
            i-=1
    for i in countdown():
        print(i)
    print('********************')
    def gen(n):#斐波那契数列
        i=0
        pref=1#s[n-2]
        pres=2#s[n-1]
        cur=0#s[n]
        while i<n:
            if i<2:
                yield 1
            else:
                cur=pref+pres
                yield cur
                pref=pres
                pres=cur
            i=i+1
    if __name__=='__main__':
        for item in gen(20):
            print(item)

    输出:

    5
    4
    3
    2
    1
    ********************
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    144
    233
    377
    610
    987
    1597
    2584
    4181
    6765

      调用gen函数不会执行gen函数,它返回一个迭代器对象,第二次迭代时从yield x的下一条语句开始执行,再到下一次遇到yield。

      虽然执行流程按照函数的流程执行,但是每次执行到yield时就会中断,它使一个函数获得了迭代能力。

  • 相关阅读:
    PHP Session保存到数据库
    PHP empty操作记录
    jquery 捕捉回车事件
    滚动条样式设计IE支持
    PHP 常用字符串处理代码片段
    JQuery选择符分类汇总
    php 操作数组 (合并,拆分,追加,查找,删除等)
    救命的PHP代码
    耍耍
    标准国家代码
  • 原文地址:https://www.cnblogs.com/1605-3QYL/p/10653988.html
Copyright © 2011-2022 走看看