def triangles():
L = [1]
while True:
yield L[:len(L)] #这部分是在看了大佬的建议,然后综合前人的代码
L.append(0)
L = [L[i - 1] + L[i] for i in range(len(L))]
def main():
n = 0
results = []
for x in triangles():
print(x)
results.append(x)
n = n + 1
if n == 10:
break
if results == [
[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]
]:
print("测试成功!")
else:
print("测试失败!")
for y in results:
print(y)
原文请参考https://blog.csdn.net/daniel960601/article/details/79185523
大佬分析说原因可能是因为从generator过来的x是浅代换,所以还是以前的地址,就是带有0的那个list,导致输出的results是每一列都是带0的
原文中还用了一个比较复杂的代码,虽然看起来比较专业,但我觉得还是越简单越好(多有冒犯抱拳)
受到的启发是对list的灵活应用