Python实现杨辉三角
[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] 先说思路:我们把每一次层看作一个list, 通过一个for循环,通过迭代, 每次生成一个list,而生成器就在每一行生成list中起作用,我们先定义 一个函数,作用是生成每一行的list对于每一行,list 的第一个元素和最 后一个元素是不变的。如果用L = [] 表示的话, L[0], L[n],是 不变的 def yhTriangle(n): l, index = [1], 0 while index < n: yield l l = [1] + [l[i] + l[i + 1] for i in range(len(l) - 1)] + [1] index += 1 for i in yhTriangle(10): print(i) 结果: [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]