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