How to deep copy a list?(如何深拷贝一个列表?)
问题描述
E0_copy = list(E0)
之后,我猜E0_copy
是E0
的深拷贝,因为id(E0)
不等于 id(E0_copy)
.然后我在循环中修改了E0_copy
,为什么后面的E0
就不一样了?
After E0_copy = list(E0)
, I guess E0_copy
is a deep copy of E0
since id(E0)
is not equal to id(E0_copy)
. Then I modify E0_copy
in the loop, but why is E0
not the same after?
E0 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for k in range(3):
E0_copy = list(E0)
E0_copy[k][k] = 0
#print(E0_copy)
print E0 # -> [[0, 2, 3], [4, 0, 6], [7, 8, 0]]
推荐答案
E0_copy
不是深拷贝.您不会使用 list()
进行深层复制.(list(...)
和 testList[:]
都是浅拷贝.)
E0_copy
is not a deep copy. You don't make a deep copy using list()
. (Both list(...)
and testList[:]
are shallow copies.)
您使用 copy.deepcopy(...)
用于深度复制列表.
You use copy.deepcopy(...)
for deep copying a list.
deepcopy(x, memo=None, _nil=[])
Deep copy operation on arbitrary Python objects.
请参阅以下片段 -
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]
现在看deepcopy
操作
>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]
为了解释,list(...)
不会递归地复制内部对象.它只复制最外层列表,同时仍然引用相同的内部列表,因此,当您改变内部列表时,更改会反映在原始列表和浅表副本中.通过检查 id(a[0]) == id(b[0])
where b = list(a)
可以看到浅拷贝引用了内部列表.
To explain, list(...)
does not recursively make copies of the inner objects. It only makes a copy of the outermost list, while still referencing the same inner lists, hence, when you mutate the inner lists, the change is reflected in both the original list and the shallow copy. You can see that shallow copying references the inner lists by checking that id(a[0]) == id(b[0])
where b = list(a)
.
这篇关于如何深拷贝一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何深拷贝一个列表?


基础教程推荐
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01