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[:]
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
