Python-字典 深拷贝&浅拷贝

来源:互联网 发布:lomo风格 知乎 编辑:程序博客网 时间:2024/05/18 02:37

Python --字典

类似其他的hash,关联数组,key-value,key不可变。

创建字典

方法1:dict1 = {1:'one',2:'two',3,"three"}

dict1 = {} //空字典

方法2: dict(mapping) -> new dictionary initialized from a mapping object's  (key, value) pairs

t1 = ((1,'one'),(2,'two'))   #元组不可变类型

dict2 = dict(t1) #工厂函数

dict2 = dict()

访问字典

通过key访问value

one = dict1[1]  # 1 是 key

方法

1.D.clear()   与 D = {} 的区别?   #D为字典

>>> dict1 = {1:'one',2:"two",3:"three"}

>>> dict2 = dict1  #赋值是将dict2这个引用指向dict1指向的字典

>>> hex(id(dict1))

'0x25149b56f48'

>>> hex(id(dict2))

'0x25149b56f48'

>>> dict1 = {}

>>> dict1

{}

>>> dict2    

{1: 'one', 2: 'two', 3: 'three'}

>>> hex(id(dict1)) # 创建了一个新的空字典

'0x25149bc5ec8'

>>> hex(id(dict2))

'0x25149b56f48'

>>> dict1 = dict2

>>> dict1.clear() #与dict1的引用指向相同的都置空

>>> dict1

{}

>>> dict2

{}

>>> hex(id(dict1))

'0x25149b56f48'

>>> hex(id(dict2))

'0x25149b56f48'

2.D.copy()   

>>> dict1 = {1:'one',2:'two'}

>>> dict2 = dict1.copy() #浅拷贝

>>> hex(id(dict1))

'0x25149bc6748'

>>> hex(id(dict2))

'0x25149bc5ec8'

浅拷贝(shallow copy)  VS 深拷贝(deep copy) 在copy

compound objects (objects that contain other objects, like lists or class instances) 时有区别

>>> import copy

>>> a = [1,2,3]

>>> b = [4,5,6]

>>> c = [a,b]

#普通的赋值

>>> d = c

>>> print(id(c) == id(d))

True

>>> print(id(c[0]) == id(d[0])

)

True

#浅拷贝

sd = copy.copy(c)

>>> print(id(sd) == id(c))

False

>>> print(id(sd[0]) == id(c[0])) #引用的拷贝

True

#深拷贝

>>> dd = copy.deepcopy(c)

>>> print(id(dd)==id(c))

False

>>> print(id(dd[0]) == id(c[0])) #新建的对象

False


参考链接

1.http://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm

2http://www.jianshu.com/p/efa9dd51f5cc



0 0
原创粉丝点击