generator 生成器
L=[i*i for i in range(10)]
print(L)
G=(i*i for i in range(10)) #变中括号为小括号
print(G)
另一种方法:
fib(max):
n,a,b=0,1,1
while n<max:
#print(b)
yield b
a,b=b,a+b
n+=1
return 'done'
但是用for
循环调用generator时,发现拿不到generator的return
语句的返回值。如果想要拿到返回值,必须捕获StopIteration
错误,返回值包含在StopIteration
的value
中:
g = fib(6) while True: try: x = next(g) print('g:', x) except StopIteration as e: print('Generator return value:', e.value) break g: 1 g: 1 g: 2 g: 3 g: 5 g: 8 Generator return value: done