我在看这个人的帖子: https://stackoverflow.com/a/2573965/1959054
他说的是通过询问以下代码的输出来测试人们的 Python 熟练程度:
x = 42
y = x
x = x+1
print x
print y
x = [1,2,3]
y = x
x[0]=4
print x
print y
我刚刚在一本书中读到有关可变列表和不可变字符串的类似场景,因此我成功预测了这两个输出。然后他举了这个例子:
x = ["foo",[1,2,3],10.4]
y = list(x)
y[0] = 'foooooo'
y[1][0] = 4
print x
print y
这让我很困惑。你看,我预测 x 会打印为 ["foo",[1,2,3],10.4] 而 y 会打印作为 ["foooooo",[4,2,3],10.4]。
x 实际上打印为 ["foo",[4,2,3],10.4],这意味着,即使外部列表引用了不同的 >list 对象,x[1] 和 y[1] 处的内部列表仍然引用同一个对象。
我以前没遇到过这个。
我的主要问题是,如果你想让 y 等同于 x,但不引用相同的列表,并且还要确保没有引用任何嵌套列表同样的列表,你是怎么做到的? y = list(x) 似乎只处理外部列表。
我的第二个问题只是在概念上获得任何帮助来理解为什么会这样工作。
请您参考如下方法:
您的第一个问题由 copy.deepcopy() 回答,其中 ( docs ):
constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
from copy import deepcopy
y = deepcopy(x)
至于为什么会发生这种情况,list() 中的标准列表构造(以及常见的 slice 副本 x[:])创建只有一个浅拷贝,即(再次文档,强调我的):
constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
