python 基础(十五)生成器

'''
生成器:
1、只有在调用时才会生成相应的数据;只记录当前位置,不能后退也不能跳跃前进,只能通过__next__()方法向下走,或for循环
'''
#斐波那契数列
def fid(max):
    n,a,b = 0,0,1
    while n < max:
        print(b)
        a,b = b,a+b
        #b,a+b相当于定义了一个新的变量t,例子如下
#        a, b = 0, 1
#       t = (b, a + b)
#        print(t[0])
#        print(t[1])
        n = n+1
    return 'done'
fid(10)

把其中的print(),换为 yield 就是生成器了,其区别在与,带有 yield 的函数不会直接执行,调用几次执行几次

def fid1(max):
    n,a,b = 0,0,1
    while n < max:
        yield b
        a,b = b,a+b
        n = n+1
    return 'done'
print(fid1(1) )  #结果是:<generator object fid1 at 0x0000019958363190>

可以通过__next__() 调用,每次调用执行一次

def fid1(max):
    n,a,b = 0,0,1
    while n < max:
        yield b
        a,b = b,a+b
        n = n+1
    return 'done'
f = fid1(3)
print(f.__next__() )
print(f.__next__() )

或通过 for 循环打印,但不会打印出return的值

def fid1(max):
    n,a,b = 0,0,1
    while n < max:
        yield b
        a,b = b,a+b
        n = n+1
    return 'done'
for i in f:     #for循环可以打印,但不会打印出return的值
    print(i)

建议通过以下这种方式:

def fid1(max):
    n,a,b = 0,0,1
    while n < max:
        yield b
        a,b = b,a+b
        n = n+1
    return 'done'
i = fid1(20)
while True:     #捕获异常并显示;下面tey的代码出现了 StopIteration 异常,就会捕捉并打印出来
    try:
        x = next(i)    #next:内置方法,同__next__()
        print('本次值为:',x)
    except StopIteration as e:
        print('返回值为:',e.value)
        break
原文地址:https://www.cnblogs.com/zbvc/p/13131735.html