Python3 复制和深浅copy

时间:2022-12-30 04:22:30

赋值:

列表的赋值:

  list1 = ['peter','sam']
list2 = list1 print(list1,id(list1))
print(list2,id(list2))
list1.append('hery')
print(list1,id(list1))
print(list2,id(list2)) ['peter', 'sam'] 5071496
['peter', 'sam'] 5071496
['peter', 'sam', 'hery'] 5071496
['peter', 'sam', 'hery'] 5071496

字典的赋值:

 dic = {'name':'just'}
dic1 = dic print(dic,id(dic))
print(dic1,id(dic1)) dic['age'] = 27 print(dic,id(dic))
print(dic1,id(dic1)) {'name': 'just'} 38505064
{'name': 'just'} 38505064
{'name': 'just', 'age': 27} 38505064
{'name': 'just', 'age': 27} 38505064

字符串赋值:

 str = 'hello'
str1 = str print(str,id(str))
print(str1,id(str1)) str = str.replace('e','E') print(str,id(str))
print(str1,id(str1)) hello 35026176
hello 35026176
hEllo 39638608
hello 35026176

创建两个相同的变量,他们的内存地址相同(以前版本好像是不同)

 str = 'h'
str3 = 'h' print(str,id(str))
print(str3,id(str3))
print( str is str3) h 39056528
h 39056528
True

浅copy:

浅copy来说,第一层创建的是新的内存地址。而从第二层开始,指向的是同一个内存地址,所有,对于第二层以及更深的层数来说,保持一致性。
 just = ['eric','bob',34,'ida']
dep = ['helo','welcome','jams']
jesp = just.copy() print(just,id(just))
print(jesp,id(jesp)) ['eric', 'bob', 34, 'ida'] 37435528
['eric', 'bob', 34, 'ida'] 37497480
 just = ['eric','bob',34,'ida']
dep = ['helo','welcome','jams']
just.append(dep)
jesp = just.copy()
just[1] = 'tom'
jesp[4][0] = 'hi' print(just,id(just))
print(jesp,id(jesp)) ['eric', 'tom', 34, 'ida', ['hi', 'welcome', 'jams']] 42744008
['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43021128

深copy:

对深copy来说,两个是完全独立的,改变任意一个元素(无论是多少层),另一个不会随着改变。

 import copy
just = ['eric','bob',34,'ida']
dep = ['helo','welcome','jams']
just.append(dep)
jesp = copy.deepcopy(just)
just[1] = 'tom'
jesp[4][0] = 'hi' print(just,id(just))
print(jesp,id(jesp)) ['eric', 'tom', 34, 'ida', ['helo', 'welcome', 'jams']] 43071752
['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43348872