旅の途中
你知道阿基米德原理吗?

导航

 

一个生成杨辉三角的例子:

def yh_triangle(line):
    a=[1] # 本次的序列
    n=0
    while n<line:
        b=[1] # 下次应返回的序列
        for i in range(len(a)-1):
            b.append(a[i]+a[i+1])
        b.append(1)
        n=n+1
        yield a # 每次执行到此处返回
        a=b

f=yh_triangle(10)

for i in f:
    print (i)

另外最后输出也可采用while True循环,通过捕获StopIteration异常来停止

while True:
    try:
        x=next(f)
        print(x)
    except StopIteration as e:
        break
posted on 2017-09-27 14:55  CknightX  阅读(125)  评论(0编辑  收藏  举报