首页 > 编程语言 > 详细

Python yield解析

时间:2019-04-04 12:42:36      阅读:146      评论:0      收藏:0      [点我收藏+]

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

Python yield解析

原文:https://www.cnblogs.com/1605-3QYL/p/10653988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!