把杨辉三角每一行看做一个list,试写一个generator,不断输出下一行的list:

杨辉三角定义如下:

          1
        1   1
      1   2   1
    1   3   3   1
  1   4   6   4   1
1   5   10  10  5   1

生成杨辉三角的代码如下所示:(L输出的是杨辉三角中的一行组成的一个序列,而triangles函数输出的是由不断循环的许多L不断更新所组成的很多序列---杨辉三角)
# -*- coding: utf-8 -*-
def triangles():
    L=[1]
    while True:
        yield L
        L.append(0)
        L = [L[i-1]+L[i] for i in range(len(L))]

其中:

L = [L[i-1]+L[i] for i in range(len(L))],这个代码是L随着i的取值变化生成一个序列,i的取值范围决定了序列中元素的个数。
 
原文地址:https://www.cnblogs.com/cccmon/p/7895037.html