两个列表的深层复制
Deepcopy of two lists
我在 python 中有两个列表,它们以不同的方式(例如顺序)存储一些 class 实例。现在,出于某种目的(独立于现有列表),我想创建这两个列表的副本。为了清楚地说明我的问题,我在下面创建了一个演示代码。
import copy
class Node:
def __init__(self):
self.node_id = 0
node = Node()
list1 = [node]
list2 = [node]
u_list1 = copy.deepcopy(list1)
u_list2 = copy.deepcopy(list2)
id1 = id(list1[0])
id2 = id(list2[0])
u_id1 = id(u_list1[0])
u_id2 = id(u_list2[0])
通过使用deepcopy操作,我创建了两个独立于list1
和list2
的新列表u_list1
和u_list2
,这就是我需要的。但是,我发现一个问题。 u_list1
和 u_list2
中的节点实例现在也是独立的。它们在内存中有不同的地址。是否有可能 u_list1
和 u_list2
中的相同实例仍然共享一个地址,就像 list1
和 list2
中的实例一样?
我需要的是id1 = id2
,u_id1 = u_id2
,而id1 != u_id1
.
您可以通过将它们一起深度复制来使用 deepcopy
的备忘录方面:
u_list1, u_list2 = copy.deepcopy((list1, list2))
来自 documentation(强调我的):
Two problems often exist with deep copy operations that don’t exist with shallow copy operations:
Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.
The deepcopy() function avoids these problems by:
- keeping a memo dictionary of objects already copied during the current copying pass; and
我在 python 中有两个列表,它们以不同的方式(例如顺序)存储一些 class 实例。现在,出于某种目的(独立于现有列表),我想创建这两个列表的副本。为了清楚地说明我的问题,我在下面创建了一个演示代码。
import copy
class Node:
def __init__(self):
self.node_id = 0
node = Node()
list1 = [node]
list2 = [node]
u_list1 = copy.deepcopy(list1)
u_list2 = copy.deepcopy(list2)
id1 = id(list1[0])
id2 = id(list2[0])
u_id1 = id(u_list1[0])
u_id2 = id(u_list2[0])
通过使用deepcopy操作,我创建了两个独立于list1
和list2
的新列表u_list1
和u_list2
,这就是我需要的。但是,我发现一个问题。 u_list1
和 u_list2
中的节点实例现在也是独立的。它们在内存中有不同的地址。是否有可能 u_list1
和 u_list2
中的相同实例仍然共享一个地址,就像 list1
和 list2
中的实例一样?
我需要的是id1 = id2
,u_id1 = u_id2
,而id1 != u_id1
.
您可以通过将它们一起深度复制来使用 deepcopy
的备忘录方面:
u_list1, u_list2 = copy.deepcopy((list1, list2))
来自 documentation(强调我的):
Two problems often exist with deep copy operations that don’t exist with shallow copy operations:
Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.
The deepcopy() function avoids these problems by:
- keeping a memo dictionary of objects already copied during the current copying pass; and