生成器属于特殊的迭代器,在函数中定义关键字yield,会返回一个迭代器对象并暂停,并在下一次执行 next() 方法时从当前位置继续运行
def feibonaqi(n): # 生成器函数 - 斐波那契a, b, count = 0, 1, 0while True:if (count > n):return# 执行一次next时到这里暂停,下面代码未执行,# 第二次执行next时,从下面的代码开始执行,for循环相当于不断调用next,直到结束yield aa, b = b, a + bcount += 1f = feibonaqi(15) # f 是一个迭代器,由生成器返回生成
for i in f:print(i,end=' ')返回结果:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610