Python -- 生成器
杨辉三角
把每一行看作一个list,试写一个 generator,不断输出下一行的list。
期待输出:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4. 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
代码:
1 # -*- coding: utf-8 -*- 2 def triangles(): 3 L = [1] 4 while True: 5 yield L 6 L.append(0) 7 L = [L[i-1]+L[i] for i in range(len(L))] 8 n = 0 9 results = [] 10 for t in triangles(): 11 print(t) 12 results.append(t) 13 n = n + 1 14 if n == 10: 15 break
理解第7行
Step1: L = [L[i-1]+L[i] for i in [1,0])]
Step2: L = [(L[-1]+L[0]), (L[0]+L[1]) ]
Step3: L = [(0+1),(1+0) ] = [1, 1]