天天看點

python fromkeys() 建立字典

# d = dict.fromkeys("張無忌","趙敏") #建立字典
# print(d)#{'張': '趙敏', '無': '趙敏', '忌': '趙敏'}      
# 傳回新字典,和原來的字典沒有關系      
# dic = {}
# d = dic.fromkeys("風扇哥","很困")
# print(dic)# {}
# print(d)#{'風': '很困', '扇': '很困', '哥': '很困'}      
# 如果value是可變的資料類型,
# 那麼其中一個key對應的value執行更改操作,其他的也跟着改變      
d = dict.fromkeys("胡辣湯",[])
print(d)#{'胡': [], '辣': [], '湯': []}
# print(id(d["胡"]))#1797375051912
# print(id(d["辣"]))#1797375051912
# print(id(d["湯"]))#1797375051912
#說明這幾個還是同一個[]  是以對其中一個進行改變别的也進行相應的改變
# d["胡"] .append("湖南特色")
# print(d)#{'胡': ['湖南特色'], '辣': ['湖南特色'], '湯': ['湖南特色']}      

指派(共用一個對象)

python fromkeys() 建立字典
# lst1 = ["胡辣湯","麻辣香鍋","灌湯包","油潑面"]
# lst2 = lst1 #并沒有産生新對象.隻是一個指向(記憶體位址)的指派
# print(id(lst1))#2253612239048
# print(id(lst2))#2253612239048

# lst1.append("葫蘆娃")
# print(lst1)#['胡辣湯', '麻辣香鍋', '灌湯包', '油潑面', '葫蘆娃']
# print(lst2)#['胡辣湯', '麻辣香鍋', '灌湯包', '油潑面', '葫蘆娃']      

淺拷貝(建立對象)

python fromkeys() 建立字典
# lst1 = ["胡辣湯","麻辣香鍋","灌湯包","油潑面"]
# lst2 = lst1.copy() #拷貝,抄作業,可以幫我們建立新的對象,和原來一模一樣,淺拷貝
# print(id(lst1))#2232732993736
# print(id(lst2))#2232732993672
#
# lst1.append("葫蘆娃")
# print(lst1)#['胡辣湯', '麻辣香鍋', '灌湯包', '油潑面', '葫蘆娃']
# print(lst2)#['胡辣湯', '麻辣香鍋', '灌湯包', '油潑面']      

淺拷貝(隻拷貝第一層内容)

python fromkeys() 建立字典
# lst1 = ["胡辣湯", "灌湯包", "油潑面", "麻辣香鍋", ["長白山", "白洋澱", "黃鶴樓"]]
# lst2 = lst1.copy() #淺拷貝,隻拷貝第一層内容
#
# print(id(lst1))#1199044806792
# print(id(lst2))#1199044806984
# print(lst1)
# print(lst2)
#
# lst1[4].append("葫蘆娃")
# print(lst1)
# print(lst2)      

深拷貝

import copy

lst1 = ["胡辣湯", "灌湯包", "油潑面", "麻辣香鍋", ["長白山", "白洋澱", "黃鶴樓"]]
lst2 = copy.deepcopy(lst1)#深拷貝 對象内部的所有内容都要複制一份.深度克隆 原型模式
print(id(lst1))#2150506176840
print(id(lst2))#2150506178120

print(lst1)#['胡辣湯', '灌湯包', '油潑面', '麻辣香鍋', ['長白山', '白洋澱', '黃鶴樓']]
print(lst2)#['胡辣湯', '灌湯包', '油潑面', '麻辣香鍋', ['長白山', '白洋澱', '黃鶴樓']]
lst1[4].append("葫蘆娃")
print(lst1)#['胡辣湯', '灌湯包', '油潑面', '麻辣香鍋', ['長白山', '白洋澱', '黃鶴樓', '葫蘆娃']]
print(lst2)#['胡辣湯', '灌湯包', '油潑面', '麻辣香鍋', ['長白山', '白洋澱', '黃鶴樓']]      

繼續閱讀