如V3.7(https://docs.python.org/3/library/copy.html)的python文档中所述
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
我试图通过将对一个列表的引用传递给另一个列表来创建如下的复合对象,并且按照我正在阅读的书,新列表L必须存储对X的引用,并且如果X更改L也必须更改。 / p>
X = [1, 2, 3]
L = ['a', X, 'b']
但是在我的IDLE上运行的测试中,我可以看到L包含对象[1,2,3]
,因此没有存储对X的引用,因此我通过更改X对此进行了测试,但这并不影响L:
>>> X = [1, 2, 3]
>>> L = ['a', X, 'b']
>>> X
[1, 2, 3]
>>> X=[1,2]
>>> L
['a', [1, 2, 3], 'b']
>>> X
[1, 2]
我的问题是:
在python 3+中确实具有更改对对象的嵌入引用的含义。如果是,那么这是否意味着浅层复制和深层复制不再区别开,这意味着它们都复制了对象的深层副本,如我的测试所示,与文档相反。
>>> L.copy()
['a', [1, 2, 3], 'b']
>>> import copy
>>> copy.deepcopy(L)
['a', [1, 2, 3], 'b']
>>>
答案 0 :(得分:2)
X=[1,2]
将名称X
重新绑定到 new 对象。修改原始对象的工作符合预期:
>>> import copy
>>> X=[1,2,3]
>>> L = [1, X, 2]
>>> L
[1, [1, 2, 3], 2]
>>> L_ = copy.copy(L)
>>> L_
[1, [1, 2, 3], 2]
>>> X.append('WOW') # modify here
>>> L, L_
([1, [1, 2, 3, 'WOW'], 2], [1, [1, 2, 3, 'WOW'], 2]) # the change is reflected in both objects