Python 中的浅拷贝和深拷贝
1. 列表和字典,直接赋值,都是浅拷贝,即赋值双方指向同一地址,因为 Python 对可变对象按引用传递。
>>> a = [1, 2, 3]>>> b = a
>>> b
[1, 2, 3]
>>> a[0] = 'apple'
>>> a
['apple', 2, 3]
>>> b
['apple', 2, 3]
>>>
>>>
>>> dic = {'a': 'apple', 'b': 'banbana'}
>>> dic2 = dic
>>> dic2
{'a': 'apple', 'b': 'banbana'}
>>> dic['b'] = 'blueberry'
>>> dic
{'a': 'apple', 'b': 'blueberry'}
>>> dic2
{'a': 'apple', 'b': 'blueberry'}
2. 对非嵌套的列表,使用完全切片[:], 工厂函数 list(),或者 copy.copy() 都是深拷贝。
>>> a = [1, 2, 3]>>> b = list(a)
>>> c = a[:]
>>> import copy
>>> d = copy.copy(a)
>>>
>>> a[0] = 'apple'
>>> a
['apple', 2, 3]
>>> b
[1, 2, 3]
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]
3. 对于非嵌套的字典,使用工厂函数 dict(),或者 copy.copy() 都是深拷贝。
>>> dic = {'a': 'apple', 'b': 'banana'}>>> dic2 = dict(dic)
>>> import copy
>>> dic3 = copy.copy(dic)
>>>
>>> dic['b'] = 'blueberry'
>>> dic
{'a': 'apple', 'b': 'blueberry'}
>>> dic2
{'a': 'apple', 'b': 'banana'}
>>> dic3
{'a': 'apple', 'b': 'banana'}
4. 对于嵌套的列表,嵌套的字典,只能使用 copy.deepcopy() 实现深拷贝。
>>> import copy>>>
>>> a = [1, 2, ['apple']]
>>> b = copy.deepcopy(a)
>>> a[2][0] = 'watermelon'
>>> a
[1, 2, ['watermelon']]
>>> b
[1, 2, ['apple']]
>>>
>>>
>>> dic = {'a': 'apple', 'b': {'b1': 'banana', 'b2': 'blueberry'}}
>>> dic2 = copy.deepcopy(dic)
>>> dic['b']['b1'] = 'bukeneng'
>>> dic
{'a': 'apple', 'b': {'b1': 'bukeneng', 'b2': 'blueberry'}}
>>> dic2
{'a': 'apple', 'b': {'b1': 'banana', 'b2': 'blueberry'}}
5. 对于嵌套可变对象的元组,只有 copy.deepcopy() 实现深拷贝。
>>> import copy
>>>>>> t = (1, 2, ['apple'])
>>> t2 = t
>>> t3 = tuple(t)
>>> t4 = copy.copy(t)
>>> t5 = copy.deepcopy(t)
>>>
>>> t[2][0] = 'watermelon'
>>> t
(1, 2, ['watermelon'])
>>> t2
(1, 2, ['watermelon'])
>>> t3
(1, 2, ['watermelon'])
>>> t4
(1, 2, ['watermelon'])
>>> t5
(1, 2, ['apple'])
完。
以上是 Python 中的浅拷贝和深拷贝 的全部内容, 来源链接: utcz.com/z/387191.html