# 刚学习 Python 中的生成器，要用生成器生成杨辉三角形。我写的生成器最终执行的结果是错误的，但是每次使用 next() 执行结果似乎是对的。不理解为什么，可能和 list 是可变的有关

``````def triangles():
result = [1]
while True:
yield result
resultcpy = result
result = []
resultcpy.insert(0,0)
for i in list(range(len(resultcpy)-1)):
result.append(resultcpy[i]+resultcpy[i+1])
result.append(1)
return "done"``````

``````>>>g = triangles()
>>>next(g)
>>>next(g)``````

``````n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break

for t in results:
print(t)``````

``````[0, 1]
[0, 1, 1]
[0, 1, 2, 1]
[0, 1, 3, 3, 1]
[0, 1, 4, 6, 4, 1]
[0, 1, 5, 10, 10, 5, 1]
[0, 1, 6, 15, 20, 15, 6, 1]
[0, 1, 7, 21, 35, 35, 21, 7, 1]
[0, 1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]``````

``````[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]``````

（网上有生成成功的答案，写得很好，但是不知道自己的错误在哪里，困于心，衡于虑，振作不起来...）

...全文
72 回复 打赏 收藏 转发到动态 举报

5,913

• 近7日
• 近30日
• 至今