【问题标题】:Difference between cloning and deepcopy?克隆和深拷贝的区别?
【发布时间】:2012-04-27 17:11:41
【问题描述】:

我刚刚开始编程,正在研究 Python 的“如何像计算机科学家一样思考”。在第 9 章进行练习之前,我没有遇到任何问题:

def add_column(matrix):

    """
    >>> m = [[0, 0], [0, 0]]
    >>> add_column(m)
    [[0, 0, 0], [0, 0, 0]]
    >>> n = [[3, 2], [5, 1], [4, 7]]
    >>> add_column(n)
    [[3, 2, 0], [5, 1, 0], [4, 7, 0]]
    >>> n
    [[3, 2], [5, 1], [4, 7]]
    """

代码应该使上述 doctest 通过。我被困在最后一个测试中:让原始列表不受影响。我查找了解决方案,如下:

x = len(matrix)

matrix2 = [d[:] for d in matrix]
for z in range(x):
    matrix2[z] += [0]
return matrix2

我的问题是:为什么第二行不能是:

matrix2 = matrix[:]

当这一行就位时,原始列表将被编辑以包含添加元素。 “如何成为..”指南听起来像是克隆创建了一个新列表,可以在不影响原始列表的情况下对其进行编辑。如果这是真的,这里发生了什么?如果我使用:

matrix2 = copy.deepcopy(matrix)

一切正常,但我并不认为克隆会失败...... 任何帮助将不胜感激!

【问题讨论】:

    标签: python cloning deep-copy


    【解决方案1】:

    在您的情况下,matrix 包含其他列表,因此当您执行 matrix[:] 时,您正在克隆包含对其他列表的引用的 matrix。那些也没有克隆。因此,当您编辑这些时,它们在原始matrix 列表中仍然相同。但是,如果您将项目附加到副本 (matrix[:]),它将不会附加到原始列表。

    要对此进行可视化,您可以使用id 函数,该函数为每个对象返回一个唯一编号:请参阅the docs

    a = [[1,2], [3,4], 5]
    print 'id(a)', id(a)
    print '>>', [id(i) for i in a]
    
    not_deep = a[:]
    # Notice that the ids of a and not_deep are different, so it's not the same list
    print 'id(not_deep)', id(not_deep)
    # but the lists inside of it have the same id, because they were not cloned!
    print '>>', [id(i) for i in not_deep]
    
    # Just to prove that a and not_deep are two different lists
    not_deep.append([6, 7])
    print 'a items:', len(a), 'not_deep items:', len(not_deep)
    
    import copy
    deep = copy.deepcopy(a)
    # Again, a different list
    print 'id(deep)', id(deep)
    # And this time also all the nested list (and all mutable objects too, not shown here)
    # Notice the different ids
    print '>>', [id(i) for i in deep]
    

    还有输出:

    id(a) 36169160
    >> [36168904L, 35564872L, 31578344L]
    id(not_deep) 35651784
    >> [36168904L, 35564872L, 31578344L]
    a items: 3 not_deep items: 4
    id(deep) 36169864
    >> [36168776L, 36209544L, 31578344L]
    

    【讨论】:

    • 我想我明白了......所以如果“矩阵”不包括嵌套列表,我会没事的,因为只有一个级别可以克隆?这就是 deepcopy 起作用的原因——它会向下复制每个级别,甚至是嵌套列表……我猜“如何成为……”是在尝试更明智的方法之前尝试完整地教授最基本的概念,但是它最终让我感到困惑。谢谢!
    【解决方案2】:

    假设您有嵌套列表,复制只会复制对这些嵌套列表的引用。

    >>> a = [1]
    >>> b = [2]
    >>> c = [a, b]
    >>> c
    [[1], [2]]
    >>> d = c[:]
    >>> d
    [[1], [2]]
    >>> d[1].append(2)
    >>> d
    [[1], [2, 2]]
    >>> c
    [[1], [2, 2]]
    

    至于哪里,copy.deepcopy():

    >>> d = copy.deepcopy(c)
    >>> d[1].append(2)
    >>> c
    [[1], [2]]
    >>> d
    [[1], [2, 2]]
    

    任何可变项都是如此。 copy.deepcopy() 将尝试确保它们也被复制。

    同样值得注意的是,使用d = c[:] 复制列表无论如何都不是一个非常清晰的语法。一个更好的解决方案是d = list(c)list() 从任何可迭代对象中返回一个新列表,包括另一个列表)。更明显的是copy.copy()

    【讨论】:

    • 感谢您的帮助-我想我现在明白了。您是否有任何理由要制作矩阵的离散副本但将嵌套列表保持在引用同一对象的范围内?我对这个过程的了解还不够远,无法预见除了令人困惑之外还有什么...
    • 这与其说是设计决策,不如说是对 Python 工作方式的影响。每当您在 Python 中赋值时,您都不会复制对象,您只需将变量分配为对它的引用。随意做其他事情是没有意义的。
    猜你喜欢
    • 2011-09-05
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2020-10-07
    • 2016-05-07
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多