问题描述
假设我有一个向量 a
定义为:
a = [[1,2,3],[-1,-2,-3]]
我了解到要创建对象 a
的副本而不引用它,我应该使用以下语法:
b = a[:]
确实,如果我执行以下语句:
b = []打印一个
输出是
>>>[[1,2,3],[-1,-2,-3]]正如我所料.不过,如果我执行以下操作:
b = a[:]b[0][2] = '改变一个'打印一个
输出是
>>>[[1,2,'改变一个'],[-1,-2,-3]]所以我很清楚对象 a[0]
正在被引用,即使包含在 a
中.如何创建对象 a
的副本,即使它的所有内部对象都不会被引用?
为此使用 deepcopy
:
Deepcopy:https://docs.python.org/2/library/copy.html#copy.deepcopy
扩展
Deepcopy 还会创建类实例的单独副本.请看下面的简单例子.
from copy import deepcopyA类:def __init__(self):self.val = 'A'>>>a = A()>>>b = 深拷贝(a)>>>b.val = 'B'>>>打印 a.val'一种'>>>打印 b.val'乙'
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
without referencing it I should use the following syntaxis:
b = a[:]
Indeed, if I execute the following statements:
b = []
print a
the output is
>>> [[1,2,3],[-1,-2,-3]]
exactly as I was expecting. Though, if I do the following:
b = a[:]
b[0][2] = 'change a'
print a
the output is
>>> [[1,2,'change a'],[-1,-2,-3]]
So it's clear to me that the object a[0]
is being referenced even if contained in a
. How can I create a copy of the object a
in a way that even all its internal objects will not be referenced?
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'
这篇关于创建不引用包含对象的列表副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!