今天学python遇到个问题,教程页面:https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128,在做作业的时候,使用其中一个网友的代码,魔改了一下
def triangles():
L = [1]
while True:
# print(L)
yield L
for x in range(1, len(L)):
L[-x] = L[-x] + L[-x - 1]
# print(L)
L=L+[1]
# print(L)
# 期待输出:
# [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]
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
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 t in triangles():
print('step',n+1,':',t)
print('result is',results)
results.append(t)
print('result now is', results)
n = n + 1
if n == 10:
break
打印结果发现
step 3 : [1, 2, 1]
result is [[1], [1, 2]]
result now is [[1], [1, 2], [1, 2, 1]]
step 4 : [1, 3, 3, 1]
result is [[1], [1, 2], [1, 3, 3]]
result now is [[1], [1, 2], [1, 3, 3], [1, 3, 3, 1]]
step 5 : [1, 4, 6, 4, 1]
result is [[1], [1, 2], [1, 3, 3], [1, 4, 6, 4]]
result now is [[1], [1, 2], [1, 3, 3], [1, 4, 6, 4], [1, 4, 6, 4, 1]]
仔细看会发现,第四步的时候,results[2]的值其实发生了变化,[1, 2, 1]变成了[1, 3, 3],看上去这个列表并不是append了一个数组进去,而且append了一个数组的指针进去。
修改办法1,:把triangles方法中的
yield L
# 改为以下
yield list(L)
修改办法2:把问题中的
results.append(t)
# 改为以下
results.append(t.copy)
反正就是不能直接指向那个原方法中的L,否则会产生问题……如有高手,望解答更深层次的原因。