Create a copy of the list not referencing the contained objects

前端 未结 4 767
暗喜
暗喜 2020-12-22 12:40

Say I have a vector a defined as:

a = [[1,2,3],[-1,-2,-3]]

I have learned that to create a copy of the object a w

相关标签:
4条回答
  • 2020-12-22 13:06

    If you only "shallow copy" b = a[:], each sub-list b[n] is still a reference to the same sub-list referenced at a[n]. Instead you need to do a deep(er) copy, e.g. by

    b = [l[:] for l in a]
    

    This creates a shallow copy of each sub-list, but as their contents are immutable that isn't a problem. If you have more levels of container nesting, you need copy.deepcopy as the other answers suggest.

    0 讨论(0)
  • 2020-12-22 13:10

    a[:] creates a shallow copy of the list.

    You can use the copy.deepcopy() function to recursively copy the objects, or use a list comprehension:

    b = [el[:] for el in a]
    

    This creates a new list object with shallow copies of the nested list objects in a.

    0 讨论(0)
  • 2020-12-22 13:24

    Use copy.deepcopy

    import copy
    b = copy.deepcopy(a)
    

    Quoting the docs:

    A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original

    Example:

    >>> a = list(range(1000))
    >>> b = copy.deepcopy(a)
    >>> a is b    # b is a new object
    False
    >>> 
    
    0 讨论(0)
  • 2020-12-22 13:33

    For that use deepcopy:

    >>> from copy import deepcopy
    >>> b = deepcopy(a)
    
    >>> b[0][2] = 'change a'
    >>> print a
    [[1,2,3],[-1,-2,-3]]
    

    Deepcopy: https://docs.python.org/2/library/copy.html#copy.deepcopy

    Extension

    Deepcopy also creates an individual copy of class instances. Please see simple example below.

    from copy import deepcopy
    
    class A:
        def __init__(self):
            self.val = 'A'
    
    >>> a = A()
    >>> b = deepcopy(a)
    
    >>> b.val = 'B'
    >>> print a.val
    'A'
    >>> print b.val
    'B'
    
    0 讨论(0)
提交回复
热议问题