通过斐波那契数列理解生成器
f(n)= f(n-1)+ f(n-2)
def fib(n): # a,b分别为第一项和第二项 a, b = 0, 1 x = 0 while x < n: x, a = a+b, b b = x print(x) # fib(6) def fib_gen(n): a, b = 0, 1 x = 0 while x < n: x, a = a + b, b b = x yield x f = fib_gen(6) print(f.__next__()) print(f.__next__())
普通函数时顺序执行,遇到return或者最后一行函数语句就返回。而generator,在每次调用next()的时候才执行,遇到yield语句就暂停并返回到函数外,再次被next()函数调用时从上次返回的yield语句处继续执行。
举例:
每次yield之后会返回到函数外,不会执行if newn之后的内容。
def count_down(n): print('生成器启动') while n >= 0: newn = yield n print('newn', newn) if newn: print('if') n = newn print('n =', n) else: n -= 1 cd = count_down(5) # for i in cd: # print('i=', i) # if i == 5: # cd.send(3) print(cd.__next__()) cd.send("dzw") print(cd.__next__()) print(cd.__next__()) print(cd.__next__())