作用:节省空间
使用:通过 next
/ for循环 调用
在函数中,通过 yield
返回函数值,并在下一次调用函数时,从上次那个yield
处开始运行。
简单演示:
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)
>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
练习
每行输出杨辉三角形系数list
def triangles():
L=[1]
while True:
yield L
L=[1]+[L[x]+L[x+1] for x in range(len(L)-1)]+[1]
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
print(results)