【问题标题】:In Python, to make two or more copies of a mutable object, is there a way to do that other than a deepcopy of a deepcopy (with memo)?在 Python 中,要制作可变对象的两个或多个副本,除了 deepcopy 的 deepcopy(带备忘录)之外,还有其他方法吗?
【发布时间】: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 你能解释一下你所说的分享是什么意思吗?谢谢(我还是个菜鸟)。
  • 共享 = 引用相同的对象

标签: python deep-copy


【解决方案1】:

如果您不想在调用之间进行记忆,请不要提供该参数。如果您忽略第二个参数,它会在调用期间在内部创建一个字典。

不过,要回答标题问题,您可以实现自己的递归解决方案,该解决方案与deepcopy 的作用相同,但除了在已经存在现成解决方案时进行实践之外,几乎没有理由这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2020-02-24
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    相关资源
    最近更新 更多