参考:
Note:
生成器属于迭代器
把 return 换成 yield
,函数就变成了生成器了
先建立一个函数,是一个数列 1, 2, 3, 5, 8, 13, 21 ...
,输入位置,输出数列在该位置上的数值
# 1, 2, 3, 5, 8, 13, 21
def num(n):
if n <= 2:
return n
else:
a, b = 1, 2
for i in range(n-2):
a, b = b, a+b
return b
print(num(1))
print(num(2))
print(num(3))
print(num(4))
output
1
2
3
5
下面我们对函数改造下
# 1, 2, 3, 5, 8, 13, 21
def num(n):
if n <= 2:
yield n
else:
a, b = 1, 2
for i in range(n-2):
a, b = b, a+b
yield b
注意,这里把 yield
放入了循环中
用 next
挤下牙膏
x = num(5) # 要定义一个变量接收生成器的返回值
print(type(x))
print(x)
print("next", next(x))
print("next", next(x))
print("next", next(x))
print("next", next(x))
output
<class 'generator'>
<generator object num at 0x7f8588d37fc0>
next 3
next 5
next 8
Traceback (most recent call last):
File "/home/Experiments/1.py", line 20, in <module>
print("next", next(x))
StopIteration
没错,是熟悉的味道
可以用 for
循环配合 next
,这样就不用每次等榨干报错了,才停止下来! eg
for i in range(n-2):
next(x)
用 next(x)
和 x.__next__()
是等价的