Python深度复制与浅复制

原文链接: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']]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在提笔写读感之前,我不得不花些笔墨在作者身上。无论合适与否,我都觉得有必要。他就是多次获得诺贝尔文学奖提名的中国国...
    桐梓22阅读 1,014评论 0 9
  • 最近几年,每年的这时候(高考)都特别的激动,焦虑,热泪盈眶,想到孩子们求学路上的艰辛,努力拼搏到感动自己。想到父母...
    伶丽阅读 163评论 1 4
  • 东方 - 需要用数据抓取软件读取数据charles 或者用浏览器的开发工具 network-js-刷新 集...
    心愿2016阅读 785评论 0 0
  • 我的大学同学,大部分孩子已经大学毕业。不过也有结婚生子比较晚,孩子刚刚上小学。知道我的孩子初中去国外,于是探讨孩子...
    书香云舍阅读 1,342评论 2 13
  • 时间是一湾清澈的溪流, 在不经意间, 我却错过了。 时间是一口新鲜的空气, 在嘴角旁边, 我却吹走了。 时间是一种...
    39c868912add阅读 237评论 2 3