Discuss / Python / 怎么输出的结果不正确呢

怎么输出的结果不正确呢

Topic source

def triangles(): L = [1] while True: yield L L.append(0) L = [L[i - 1] + L[i] for i in range(len(L))]

n = 0 results = [] for t in triangles(): print(t) results.append(t) n = n + 1 if n == 10: break print(results) 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('测试失败!')

结果:

[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] [[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, 0], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]] 测试失败!

Process finished with exit code 0

为什么输出的results结果不正确呀

你的results列表里每个列表的后面都多了一个 0 啊,所以不对;至于0 是怎么来的,我就没看懂了

shen愛

#3 Created at ... [Delete] [Delete and Lock User]

这是内存引用的问题,数组是可变的,但内存地址没有变 n=1时,yield 直接返回了L ,里面只有一个 [1] n=2时,会走下面的L.append(0), 这块是对L=[1]做的更改,所以n=1时的L会变成[1,0] 之后的 L = [xxx] 相当于新开辟了内存空间,但是每次yield之后都会append(0) ,所以最终打印的results后面都多了一个0 . 最后一个是yield返回了,没有走append(0),所以results最后一个没有0

补0的思想很好,可以稍微修改下

L = [1]
while True:
    yield L
    LCopy = L[:] //copy,开辟新内存地址
    LCopy.append(0)
    L = [LCopy[i - 1] + LCopy[i] for i in range(len(Lcopy))]

  • 1

Reply