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)#{'': ['湖南特色'], '': ['湖南特色'], '': ['湖南特色']}

赋值(共用一个对象)

 

# lst1 = ["胡辣汤","麻辣香锅","灌汤包","油泼面"]
# lst2 = lst1 #并没有产生新对象.只是一个指向(内存地址)的赋值
# print(id(lst1))#2253612239048
# print(id(lst2))#2253612239048

# lst1.append("葫芦娃")
# print(lst1)#['胡辣汤', '麻辣香锅', '灌汤包', '油泼面', '葫芦娃']
# print(lst2)#['胡辣汤', '麻辣香锅', '灌汤包', '油泼面', '葫芦娃']

浅拷贝(新建对象)

 

# lst1 = ["胡辣汤","麻辣香锅","灌汤包","油泼面"]
# lst2 = lst1.copy() #拷贝,抄作业,可以帮我们创建新的对象,和原来一模一样,浅拷贝
# print(id(lst1))#2232732993736
# print(id(lst2))#2232732993672
#
# lst1.append("葫芦娃")
# print(lst1)#['胡辣汤', '麻辣香锅', '灌汤包', '油泼面', '葫芦娃']
# print(lst2)#['胡辣汤', '麻辣香锅', '灌汤包', '油泼面']

浅拷贝(只拷贝第一层内容)

 

# 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)#['胡辣汤', '灌汤包', '油泼面', '麻辣香锅', ['长白山', '白洋淀', '黄鹤楼']]

 

posted @ 2018-12-08 13:26  anobscureretreat  阅读(359)  评论(0编辑  收藏  举报