在Python中,这种一边循环一边计算后面元素的机制,称为生成器:generator。
>>> g= (x*x for x in range(10)) >>> next(g) 0 >>> >>> next(g) 1 >>> next(g) 4 >>> next(g) 9 >>> next(g) 16
a = 0 b = 1 count = 0 while count < 20: tmp = a # 给新的a 赋值前 先把旧值存下来 a = b # 新的a = 1 b = tmp+ b print(a,b) count +=1
def fib(n): a = 0 b = 1 count = 0 while count < n: tmp = a # 给新的a 赋值前 先把旧值存下来 a = b # 新的a = 1 b = tmp + b #print( b) yield b # 暂停 count += 1 f = fib(20) print(next(f)) print(next(f)) print(next(f)) print(next(f))
原文:https://www.cnblogs.com/kissfire008/p/11751149.html