Python: deepcopy(list) vs new_list = old_list[:](Python:deepcopy(list) vs new_list = old_list[:])
问题描述
我正在做练习 #9,来自 http://openbookproject.net/thinkcs/python/english2e/ch09.html 并且遇到了一些没有意义的东西.
I'm doing exercise #9 from http://openbookproject.net/thinkcs/python/english2e/ch09.html and have ran into something that doesn't make sense.
该练习建议使用 copy.deepcopy()
使我的任务更轻松,但我不明白它是如何做到的.
The exercise suggests using copy.deepcopy()
to make my task easier but I don't see how it could.
def add_row(matrix):
"""
>>> m = [[0, 0], [0, 0]]
>>> add_row(m)
[[0, 0], [0, 0], [0, 0]]
>>> n = [[3, 2, 5], [1, 4, 7]]
>>> add_row(n)
[[3, 2, 5], [1, 4, 7], [0, 0, 0]]
>>> n
[[3, 2, 5], [1, 4, 7]]
"""
import copy
# final = copy.deepcopy(matrix) # first way
final = matrix[:] # second way
li = []
for i in range(len(matrix[0])):
li.append(0)
# return final.append(li) # why doesn't this work?
final.append(li) # but this does
return final
我很困惑为什么本书建议在简单的 list[:]
复制它时使用 deepcopy()
.我用错了吗?我的功能完全不正常吗?
I'm confused why the book suggests using deepcopy()
when a simple list[:]
copies it. Am I using it wrong? Is my function completely out of wack?
我也有一些混乱的返回值.问题是上面代码中的文档.
I also have some confusion returning values. the question is documents in the code above.
TIA
推荐答案
你问了两个问题:
matrix[:]
是一个浅拷贝——它只拷贝直接存储在其中的元素,不会递归地拷贝数组或其他引用的元素自身之内.这意味着:
matrix[:]
is a shallow copy -- it only copies the elements directly stored in it, and doesn't recursively duplicate the elements of arrays or other references within itself. That means:
a = [[4]]
b = a[:]
a[0].append(5)
print b[0] # Outputs [4, 5], as a[0] and b[0] point to the same array
如果您将对象存储在 a
中也会发生同样的情况.
The same would happen if you stored an object in a
.
deepcopy()
自然是一个deep copy——它递归地复制每个元素,一直沿树向下:
deepcopy()
is, naturally, a deep copy -- it makes copies of each of its elements recursively, all the way down the tree:
a = [[4]]
c = copy.deepcopy(a)
a[0].append(5)
print c[0] # Outputs [4], as c[0] is a copy of the elements of a[0] into a new array
返回
return final.append(li)
与调用 append
并返回 final
不同,因为 list.append 不返回列表对象本身, 它返回 None
Returning
return final.append(li)
is different from calling append
and returning final
because list.append does not return the list object itself, it returns None
这篇关于Python:deepcopy(list) vs new_list = old_list[:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:deepcopy(list) vs new_list = old_list[:]


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