Python采用List【列表生成式】实现【杨辉三角】生成器
实现:
# -*- coding: utf-8 -*-
def triangles():
n, b = 10, [1]
while n > 0:
yield b
b = [sum(i) for i in zip([0]+b,b+[0])]
n = n - 1
return 'done'
测试:
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
注释: zip() 函数,举个例子:
x = [x1 ,x2]
y = [y1, y2]
zip( x , y ) = [( x1 , y1 ) , (x2 , y2)]
借助的是 zip() 函数实行 “ 错位 ”,就是将列表分别进行首位补零和末尾补零,最后 利用 sum() 函数相加。
输出:
参考:廖雪峰