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[:]


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01