Python-字典 深拷貝&淺拷貝

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章