【发布时间】:2020-12-24 20:20:55
【问题描述】:
我正在阅读 deepcopy,由于使用了 memoization,看起来同一个可变对象的 deepcopy 都引用了第一个 deepcopy 产生的同一个对象(如果这有意义的话)。 (下面的问题和代码的灵感来自this。)
from copy import deepcopy
a = [1,2,3]
memo = {}
b = deepcopy(a,memo)
print(memo)
# Output was
# {140324138116224: [1, 2, 3], 140324138884096: [[1, 2, 3]]}
# The ids that are the keys in the memo dictionary above may or may not be different
# every time you run the code. In any case, getting the key for value [1, 2, 3] below:
key = list(memo.keys())[0] # key is now 140324138116224 in this code run
让我们再做一个列表“a”的深拷贝。根据works的memoization方式,c被赋予了b所指的同一个对象。
c = deepcopy(a, memo) # So is this really another deepcopy of "a", intuitively speaking?
print(id(c) == id(b)) # Output is True, so "c" and "b" refer to the same object.
print(id(c) == id(memo[key])) # Output is True.
#According to the above link, "c" is created by memo.get(key),
# so it makes sense that the above returns True
b.append(4)
print(c) #We appended to "b", yet this will output [1, 2, 3, 4]
所以如果我想对一个可变对象进行多个深拷贝,看起来我必须这样做
a = [1, 2, 3]
b = deepcopy(a, memo)
c = deepcopy(b, memo)
# etc.
像这样把它们连在一起吗?难道没有别的办法了吗?例如,如果我出于某种原因在两者之间改变“b”会怎样,比如
a = [1, 2, 3]
b = deepcopy(a, memo)
# Do some mutating stuff to "b", like
b.append(4)
# Let's say I now want another deepcopy of "a", and not of "b", since I already did some stuff to "b".
c = deepcopy(a, memo)
# But the above seems to be not what I want because this will just give me a reference to the
# same object that "b" refers to.
print(c) # Gives [1, 2, 3, 4], which is not a copy of "a".
c = deepcopy(b, memo) # Not what I want either because I already did some mutating stuff to b
我知道实际上,我会在改变“b”之前做c = deepcopy(b, memo),但我仍然想知道是否有任何其他方法可以更直观地处理复制可变对象(带备忘录)?
我想人们总是不能使用记忆,在这种情况下,b = deepcopy(a) 和 c = deepcopy(a) 将引用不同的对象,因此是“a”的直观深拷贝,但这似乎是如何使用深拷贝的细微差别这会导致截然不同的结果。
感谢您的帮助!
【问题讨论】:
-
取深拷贝的浅拷贝?
-
这不是“细微差别”,而是您应该使用它的方式。如果你不想分享,你通常会做一个深拷贝。
-
@barmar 你能解释一下你所说的分享是什么意思吗?谢谢(我还是个菜鸟)。
-
共享 = 引用相同的对象