在Python中,要创建一个可变对象的两个或多个副本,除了deepcopy的deepcopy(带有memo)之外,还有其他方法吗?
我在读deepcopy,由于使用了备忘录,看起来同一个可变对象的deepcopy都引用了第一个deepcopy生成的同一个对象(如果有意义的话)。下面的问题和代码的灵感来自 让我们再复制一份清单a。根据记忆的方式,c被分配给b所指的同一个对象在Python中,要创建一个可变对象的两个或多个副本,除了deepcopy的deepcopy(带有memo)之外,还有其他方法吗?,python,deep-copy,Python,Deep Copy,我在读deepcopy,由于使用了备忘录,看起来同一个可变对象的deepcopy都引用了第一个deepcopy生成的同一个对象(如果有意义的话)。下面的问题和代码的灵感来自 让我们再复制一份清单a。根据记忆的方式,c被分配给b所指的同一个对象 c = deepcopy(a, memo) # So is this really another deepcopy of "a", intuitively speaking? print(id(c) ==
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]
所以,如果我想制作一个可变对象的多个deepcopies,看起来我必须这么做
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=deepcopyb,memo,但我仍然想知道是否还有其他方法可以更直观地处理复制可变对象的问题
我想人们不可能总是使用备忘录,在这种情况下,b=deepcopya和c=deepcopya将引用不同的对象,因此是a的直观deepcopies,但这似乎是如何使用deepcopy的一个细微差别,导致了截然不同的结果
谢谢你的帮助 如果您不想在调用之间进行记录,请不要提供该参数。如果忽略第二个参数,它会在调用期间内部创建一个字典
不过,为了回答标题问题,您可以实现自己的递归解决方案,该解决方案与deepcopy相同,但除了在已经存在现成解决方案的情况下进行实践之外,没有什么理由这样做。对深度副本进行浅层复制?这不是细微的区别,而是您应该使用它的方式。如果你不想分享,你通常会制作一份深度拷贝。@barmar你能解释一下你所说的分享是什么意思吗?谢谢,我还是个傻瓜。共享=指的是相同的对象
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