为什么将列表元素同化到变量在这里以不同的方式工作?



我有这段代码:

lst = [[1,1], [2,1],[3,1]]
n = len(lst)
head = lst[n - 1]
head[0] += 1
lst.append(head)
del lst[0]
print(lst)

我希望打印此代码:[[2,1], [3,1], [4,1]]但它是打印:[[2, 1], [4, 1], [4, 1]].我不明白为什么。请帮助我。

当你写head = lst[n - 1]时,这会通过引用将头设置为lst的最后一个元素。这意味着值[3,1]的对由两个变量共享。如果您不想更改原始列表中的对,请确保头部复制数据。

head = lst[n - 1].copy()

满足您需求的快速解决方案是

inc_lst = [ [ x[0]+1 , x[1] ] for x in lst]

希望它会有所帮助

当您使用

head = lst[n - 1]

执行时,您获得引用 [3,1] 作为头部

head[0] += 1

您将 [[1,1]、[2,1]、[3,1]] 更改为 [[1,1]、[2,1]、[4,1]]

当你进行追加时,lst得到了另一个头的副本。

因此,在 del lst[0] 之后,你得到的结果 [[2,1], [4,1], [4,1]]

  1. lst = [[1,1], [2,1],[3,1]]
  2. n = len(lst)-n将等于 3
  3. head = lst[n - 1]=>head = lst[2]=>head = [3, 1]
  4. head[0] += 1它换头,head = [4, 1]
  5. lst.append(head),记住lst = [[1, 1], [2, 1], [4, 1]]head = [4, 1]=> [[1, 1], [2, 1], [4, 1], [4, 1]]
  6. del lst[0]=> [[2
  7. , 1], [4, 1], [4, 1]]

无论如何,当头部被[3, 1]时,你改变头部,它会自动改变lst[n - 1]

另外,请尝试使用 http://www.pythontutor.com/visualize.html

如果需要逐步了解代码的工作原理,这是一个非常有用的工具。

这实际上是编程初学者(比如我自己)中非常普遍的问题。其他问题已经回答了这个问题,但我只想提一下,这是一个"价值语义与参考语义"的案例。快速阅读此主题以避免将来出现此类错误可能会很有用。

最新更新