美文网首页
Python深度复制与浅复制

Python深度复制与浅复制

作者: 开罗酒吧 | 来源:发表于2017-05-17 13:48 被阅读0次

    原文链接:http://www.python-course.eu/deep_copy.php

    The difference between shallow and deep copying is only relevant for compound objects, which are objects containing other objects, like lists or class instances.

    >>> colours1 = ["red", "green"]
    >>> colours2 = colours1
    >>> colours2 = ["rouge", "vert"]
    >>> print colours1
    ['red', 'green']
    

    In the example above a simple list is assigned to colours1. In the next step we assign colour1 to colours2. After this, a new list is assigned to colours2. A new memory location had been allocated for colours2, because we have assigned a complete new list to this variable.

    >> colours1 = ["red", "green"]
    >>> colours2 = colours1
    >>> colours2[1] = "blue"
    >>> colours1
    ['red', 'blue']
    

    colours1 and colours2 share the same memory

    shallow copy:using [:]

    >>> list1 = ['a','b','c','d']
    >>> list2 = list1[:]
    >>> list2[1] = 'x'
    >>> print list2
    ['a', 'x', 'c', 'd']
    >>> print list1
    ['a', 'b', 'c', 'd']
    >>> 
    

    But as soon as a list contains sublists, we have the same difficulty, i.e. just pointers to the sublists.

    >>> lst1 = ['a','b',['ab','ba']]
    >>> lst2 = lst1[:]
    
    shallow_copy_4.png

    Using the Method deepcopy from the Module copy

    A solution to the described problems is to use the module "copy". This module provides the method "copy", which allows a complete copy of a arbitrary list, i.e. shallow and other lists.

    The following script uses our example above and this method:

    from copy import deepcopy
    
    lst1 = ['a','b',['ab','ba']]
    
    lst2 = deepcopy(lst1)
    
    lst2[2][1] = "d"
    lst2[0] = "c";
    
    print lst2
    print lst1
    

    If we save this script under the name of deep_copy.py and if we call the script with "python deep_copy.py", we will receive the following output:

    $ python deep_copy.py 
    ['c', 'b', ['ab', 'd']]
    ['a', 'b', ['ab', 'ba']]
    

    相关文章

      网友评论

          本文标题:Python深度复制与浅复制

          本文链接:https://www.haomeiwen.com/subject/cwjdxxtx.html