python深度复制列表_Python深度复制与浅复制

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']]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值