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时就会中断,它使一个函数获得了迭代能力。

  • 相关阅读:
    BZOJ3473: 字符串
    BZOJ1088: [SCOI2005]扫雷Mine
    跪啃SAM
    BZOJ3932: [CQOI2015]任务查询系统
    BZOJ3545: [ONTAK2010]Peaks
    06.约束
    05.数据表的创建与简单操作
    04.数据库的创建
    安卓6.0后运行时权限封装
    OkGo使用缓存
  • 原文地址:https://www.cnblogs.com/1605-3QYL/p/10653988.html
Copyright © 2011-2022 走看看