Python:deepcopy(list)vs new_list = old_list [:] [英] Python: deepcopy(list) vs new_list = old_list[:]
问题描述
我从 http://openbookproject.net/thinkcs练习#9 /python/english2e/ch09.html ,并遇到了没有意义的东西。
练习建议使用 copy
.deepcopy()
使我的任务更容易, 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
#end = copy.deepcopy(matrix)#first way
final = matrix [:]#second way
li = []
for i in range(len(matrix [0])) :
li.append(0)
#return final.append(li)#为什么这不工作?
final.append(li)#但这样做
return final
I当一个简单的列表[:]
复制它时,为什么本书建议使用 deepcopy()
我使用它错了吗?我的函数是否完全无效?
我也有一些混乱返回值。
您提出了两个问题:
深与浅拷贝
matrix [:]
是浅拷贝 - 它仅复制直接存储在其中的元素,而不会递归地复制数组元素或其自身内的其他引用。这意味着:
a = [[4]]
b = a [:]
a [0] .append(5)
print b [0]#输出[4,5]作为[0]和b [0]指向同一个数组
如果你在 a
中存储一个对象,同样会发生。
deepcopy()
当然是一个深拷贝 - 它递归地复制每个元素,
a = [[4]]
c = copy.deepcopy(a)
a [0] .append(5)
print c [0]#输出[4],因为c [0]是将[0]的元素复制到新数组
返回
return final.append li)
不同于调用 append
并返回 final
,因为list.append不返回列表对象本身,它返回 None
I'm doing exercise #9 from http://openbookproject.net/thinkcs/python/english2e/ch09.html and have ran into something that doesn't make sense.
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
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
You asked two questions:
Deep vs. shallow copy
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
The same would happen if you stored an object in a
.
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
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 [:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!