代码如下:
# 采用生成器得到斐波那契数列
def fibonacci(lenth):
a, b = 0, 1
n = 0
while n < lenth:
yield b # 返回b的值,并暂定程序在此
a, b = b, a + b
n += 1
gen = fibonacci(10)
fibonacciList = []
while True:
try:
fibonacciList.append(gen.__next__())
except:
print(fibonacciList)
print('元素个数不足!')
break
运行结果:
元素个数不足!
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]