两种方法的不同是体现在对杨辉三角的构建方式的理解不同导致。
方法一:
# [1, 2, 1]
# [1, 2, 1] 错位相加后:
# [1, 3, 3, 1] 生成下一行。
def triangles():
n = [1]
while True:
yield n
n = [x+y for x,y in zip([0] + n,n+[0])]
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
关于yield的用法,参考:https://blog.youkuaiyun.com/mieleizhi0522/article/details/82142856讲的非常清晰。
zip函数就相当于前三行的注释体现的意思。
方法二:
def triangles():
L = [1] #定义L为一个只包含一个元素的列表
while True:
yield L #定义为生成器函数
L =[1] + [L[n] + L[n-1] for n in range(1,len(L))] + [1]
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
附:对此2处for循环的理解:将其理解为一个列表,只不过这个列表由迭代器生成,实际上不存在于内存中。