生成器的作用是边循环边计算,节约内存
#定义一个生成器
def foo():
print('www')
yield 1
print('martin')
yield 2
#这里得到生成器,并不是执行函数
g = foo()
for i in g:
print(i)
www
1
martin
2
裴波那契数列
def fibo(indx):
n ,before ,after = 0,0,1
while n < indx:
yield before
before , after = after , after+before
n +=1
for i in fibo(9):
print(i,end=' ')
0 1 1 2 3 5 8 13 21