首先我们对list与dict进行深度复制,其他也一样。我知识使用了json进行转换而已
# 遍历深度复制: def deepCopy(obj): if isinstance(obj,dict): deepdata = {} for i in obj: if isinstance(obj[i],list): deepdata[i] = deepCopy(obj[i]) else: deepdata[i] = obj[i] elif isinstance(obj,list): deepdata = [] for j in range(len(obj)): if isinstance(obj[j],dict): deepdata.append(deepCopy(obj[j])) else: deepdata.append(obj[j]) else: import json deepdata = json.loads(json.dumps(obj)) return deepdata obj = {'name':'小李','age':18,'爱好':['篮球','皮球',{'文艺':['音乐','park']}]} obj1 = ['老大','老二',{'学生':20,'老师':10,'name':['小王','小七']}] obj2 = '八戒你搜了!' s9 = deepCopy(obj) print(s9)
关于复制和赋值的区别:
def func(a,b): # a = a.copy() # b = b.copy() a['name'] = a['name']+1 b['name'] = b['name']+1 print(a,' ',b) aa = {'name':5} bb = {'name':6} print(aa) print(bb) func(aa,bb) print(aa) print(bb)