Python DeepCopy不使用 *操作员删除列表中的内部参考?
我有以下代码。我通过l1*3
,DeepCopy并分配给l2
,扩展了DICS的列表(L1
)。现在,当我在l2
中修改第一个元素时,l2
中的其他相应元素也会被修改。因此,DeepCopy不会删除DICS列表上*
操作员创建的参考?
import copy
l1 = [{'a':1},{'b':2}]
l2 = copy.deepcopy(l1*3)
print(l2)
l2[0]['a'] = 7 # Why this changed ['a'] to 7 in all dicts in l2, even after deepcopy?
print(l2)
输出:
[{'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}]
[{'a': 7}, {'b': 2}, {'a': 7}, {'b': 2}, {'a': 7}, {'b': 2}]
预期:(只有第一个元素应修改)
[{'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}]
[{'a': 7}, {'b': 2}, {'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}]
我已经发现以下解决方案以获取预期输出:
l2 = [d.copy() for d in l1*3]
有人可以分享为什么DeepCopy在第一个代码中不起作用的解释。 ?
I have the following code. I extended the list of dicts (l1
) by l1*3
, deepcopy and assigned to l2
. Now when I modify first element in l2
, other corresponding elements in l2
also gets modified. So deepcopy does not remove the reference created by *
operator on list of dicts ?
import copy
l1 = [{'a':1},{'b':2}]
l2 = copy.deepcopy(l1*3)
print(l2)
l2[0]['a'] = 7 # Why this changed ['a'] to 7 in all dicts in l2, even after deepcopy?
print(l2)
Output:
[{'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}]
[{'a': 7}, {'b': 2}, {'a': 7}, {'b': 2}, {'a': 7}, {'b': 2}]
Expected: (Only first element should modify)
[{'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}]
[{'a': 7}, {'b': 2}, {'a': 1}, {'b': 2}, {'a': 1}, {'b': 2}]
I have already found following solution to get expected output:
l2 = [d.copy() for d in l1*3]
Can someone share an explanation for why the deepcopy did not work in first code. ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
deepcopy
有意复制正在复制的结构中的任何别名引用。它维护备忘录
在当前复制操作期间已经复制的对象的字典,当再次看到相同的对象时,它将别名插入已经复制的对象。除其他事项外,这使得递归数据结构安全(非遗传deepcopy
将永远恢复,直到记忆用尽并死亡)。如果您希望各个元素都不陈述,
deepcopy
单独使用,例如:分离的
deepcopy
操作维护单独的回忆字典。deepcopy
intentionally replicates any aliased references within the structure being copied. It maintains amemo
dictionary of objects already copied during the current copy operation, and when the same object is seen again, it inserts an alias to the already copied object. Among other things, this makes it safe with recursive data structures (where a non-memoizeddeepcopy
would recurse forever until it ran out of memory and died).If you want the individual elements to be unaliased,
deepcopy
them individually, e.g.:where the separated
deepcopy
operations maintain separate memoization dictionaries.