2

python中的copy.copy和copy.deepcopy函数有什么区别?

>>> copy.deepcopy(li)
[1, 2, 3, 4]

>>> copy.copy(li)
[1, 2, 3, 4]

两者都做同样的事情,谁能告诉这些功能具体做什么

4

2 回答 2

5
>>> import copy
>>> L = [[1,2,3]]
>>> A = copy.copy(L)
>>> A[0].append(4)
>>> A
[[1, 2, 3, 4]]
>>> L
[[1, 2, 3, 4]]
>>> L = [[1,2,3]]
>>> A = copy.deepcopy(L)
>>> A[0].append(4)
>>> A
[[1, 2, 3, 4]]
>>> L
[[1, 2, 3]]
于 2013-06-01T11:10:03.010 回答
3

copy.copy performs a shallow copy as opposed to copy.deepcopy which performs a deep copy.

When considering:

li = [1, 2, 3, 4]

you will not notice any difference, because you are copying immutable objects, however consider:

>>> import copy
>>> x = copy.copy(li)
>>> x
[[1, 2], [3, 4]]
>>> x[0][0] = 9
>>> li
[[9, 2], [3, 4]]

Since a shallow copy only makes copies of each reference in the list, manipulating these copied references will still affect the original list.

However the following code:

>>> x.append(1)

will have no effect on the original list.

于 2013-06-01T11:08:09.870 回答