Python教程

Python 数据类型 copy & deepcopy

本文主要是介绍Python 数据类型 copy & deepcopy,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Python数据类型
不可变 int, float, string, tuple

>>> a = 1
>>> b = 1
>>> print(id(a))
140454796502904
>>> print(id(b))
140454796502904
# a b 地址一样

>>> a = 1
>>> x = copy.copy(a)
>>> y = copy.deepcopy(a)
>>> print(a,x,y)
(1, 1, 1)
>>> print(id(a),id(x),id(y))
(140454796502904, 140454796502904, 140454796502904)
>>> a = 2
>>> print(a,x,y)
(2, 1, 1)
>>> print(id(a),id(x),id(y))
(140454796502880, 140454796502904, 140454796502904)
>>>
改变a的值,发现a指向了另一个对象,而copy和deepcopy没变,依然指向原来的1

可变 list, dict, set, class
>>> c = [1]
>>> d = [1]
>>> print(id(c), id(d))
(140454827196216, 140454827241128)
# c d 地址不同,开辟了新的地址

>>> c = [1,[2,3]]
>>> d = copy.copy(c)
>>> e = copy.deepcopy(c)
>>> print(c,d,e)
([1, [2, 3]], [1, [2, 3]], [1, [2, 3]])
>>> print(id(c), id(d), id(e))
(140454827539200, 140454827539704, 140454827241128)
>>> c[1][0] = 4
>>> print(c,d,e)
([1, [4, 3]], [1, [4, 3]], [1, [2, 3]])
>>> print(id(c), id(d), id(e))
(140454827539200, 140454827539704, 140454827241128)
>>>
# copy和deepcopy分别开辟了新的地址, 嵌套列表c改变c[1][0] = 4, copy值随之改变,deepcopy不变。如果改变c[0], copy deepcopy都不会变

>>> c = [3,[4,5]]

>>> d = copy.copy(c)

>>> e = copy.deepcopy(c)

>>> c[0] = 2

>>> print(id(c), id(d), id(e))

(140454827539344, 140454827540280, 140454827539272)

>>> print(c,d,e)

([2, [4, 5]], [3, [4, 5]], [3, [4, 5]])

>>> 

# c使用下标改变的list值,改变后地址也没变,如果是c = [1] 指向新的list,就会改变

这篇关于Python 数据类型 copy & deepcopy的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!