Python DeepCopy不使用 *操作员删除列表中的内部参考?

发布于 2025-02-12 22:34:26 字数 867 浏览 1 评论 0原文

我有以下代码。我通过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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅忆 2025-02-19 22:34:27

deepcopy 有意复制正在复制的结构中的任何别名引用。它维护备忘录在当前复制操作期间已经复制的对象的字典,当再次看到相同的对象时,它将别名插入已经复制的对象。除其他事项外,这使得递归数据结构安全(非遗传deepcopy将永远恢复,直到记忆用尽并死亡)。

如果您希望各个元素都不陈述,deepcopy单独使用,例如:

 l2 = [copy.deepcopy(x) for x in l1*3]

分离的deepcopy操作维护单独的回忆字典。

deepcopy intentionally replicates any aliased references within the structure being copied. It maintains a memo 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-memoized deepcopy 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.:

 l2 = [copy.deepcopy(x) for x in l1*3]

where the separated deepcopy operations maintain separate memoization dictionaries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文