生成器:1.只有在调用时,才会真正生成占用内存
2.内存中始终只保存“当前值”
3.只有一个方法__next__()
与函数的区别,有了yield关键字(用于保存与调取现场值)
eg1:
c=(i*2 for i in range(10))
区别列表生成式:
b=[i*2 for i in range(10)]
def fib(x):
n, a, b = 0, 0, 1
while n < x:
yield b #调取当前值,保存当前值
a, b = b, a+b
n = n+1
return 'done' #用于异常处理
f=fib(10)
while True:
try:
g = f.__next__()
print(g)
except StopIteration as e:
print('the final value:',e.value)
break
结果:
1
2
3
5
8
13
21
34
55
the final value: done