Discuss / Python / 为啥输出结果对 但是显示测试失败呢?请各位指教

为啥输出结果对 但是显示测试失败呢?请各位指教

Topic source

def triangles(): S = [1] while True: yield S S.append(0) S = [S[i-1] + S[i] for i in range(len(S))] [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] 测试失败!

JorgeBowie

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

要有切片这一步。浅拷贝、深拷贝

@JorgeBowie:简单百度了一下,大致了解了浅拷贝深拷贝的区别,但是我还是不明白这里需要再通过切片生产一个一模一样的list的用途,还望详细赐教。

April1402

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

按照下面的验证方法,打出来看看呗

S.append(0) 改成S = S + [0]

你如果想搞懂,可以跑一下我下面这一串

def ppt() : S = [1] while True: print ('{}\t1\t{}' .format(id(S), S)) yield S print ('{}\t2\t{}' .format(id(S), S)) S.append(0) print ('{}\t3\t{}' .format(id(S), S)) S = S + [2] print ('{}\t4\t{}' .format(id(S), S))

n = 0 results = [] for t in ppt(): print(t) print ('{}\t5\t{}' .format(id(t), t)) print ('{}\t6\t{}' .format(id(results), results)) results.append(t) print ('{}\t7\t{}' .format(id(results), results)) n = n + 1 if n == 4: break print ('{}\t8\t{}' .format(id(results), results)) print (results)

感觉这样会美观一点: yield S[:]

  1. 函数中返回的是变量S,这个变量被直接append到results中去了

  2. results中对应的元素和变量S指向的是同一个值,对S进行append操作的时候, S对应的值被改变了,也就是说results中对应的元素被改变了。

参见下面这个例子:

a = [1,2,3] b = a b [1, 2, 3] a.append(0) a [1, 2, 3, 0] b [1, 2, 3, 0] a = [1,2,3,4] a [1, 2, 3, 4] b [1, 2, 3, 0]


  • 1

Reply