赋值:
列表的赋值:
1 list1 = ['peter','sam'] 2 list2 = list1 3 4 print(list1,id(list1)) 5 print(list2,id(list2)) 6 list1.append('hery') 7 print(list1,id(list1)) 8 print(list2,id(list2)) 9 10 ['peter', 'sam'] 5071496 11 ['peter', 'sam'] 5071496 12 ['peter', 'sam', 'hery'] 5071496 13 ['peter', 'sam', 'hery'] 5071496
字典的赋值:
1 dic = {'name':'just'} 2 dic1 = dic 3 4 print(dic,id(dic)) 5 print(dic1,id(dic1)) 6 7 dic['age'] = 27 8 9 print(dic,id(dic)) 10 print(dic1,id(dic1)) 11 12 13 14 15 {'name': 'just'} 38505064 16 {'name': 'just'} 38505064 17 {'name': 'just', 'age': 27} 38505064 18 {'name': 'just', 'age': 27} 38505064
字符串赋值:
1 str = 'hello' 2 str1 = str 3 4 print(str,id(str)) 5 print(str1,id(str1)) 6 7 str = str.replace('e','E') 8 9 print(str,id(str)) 10 print(str1,id(str1)) 11 12 13 14 hello 35026176 15 hello 35026176 16 hEllo 39638608 17 hello 35026176
创建两个相同的变量,他们的内存地址相同(以前版本好像是不同)
1 str = 'h' 2 str3 = 'h' 3 4 print(str,id(str)) 5 print(str3,id(str3)) 6 print( str is str3) 7 8 9 10 h 39056528 11 h 39056528 12 True
浅copy:
浅copy来说,第一层创建的是新的内存地址。而从第二层开始,指向的是同一个内存地址,所有,对于第二层以及更深的层数来说,保持一致性。
1 just = ['eric','bob',34,'ida'] 2 dep = ['helo','welcome','jams'] 3 jesp = just.copy() 4 5 print(just,id(just)) 6 print(jesp,id(jesp)) 7 8 9 10 ['eric', 'bob', 34, 'ida'] 37435528 11 ['eric', 'bob', 34, 'ida'] 37497480
1 just = ['eric','bob',34,'ida'] 2 dep = ['helo','welcome','jams'] 3 just.append(dep) 4 jesp = just.copy() 5 just[1] = 'tom' 6 jesp[4][0] = 'hi' 7 8 print(just,id(just)) 9 print(jesp,id(jesp)) 10 11 12 13 ['eric', 'tom', 34, 'ida', ['hi', 'welcome', 'jams']] 42744008 14 ['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43021128
深copy:
对深copy来说,两个是完全独立的,改变任意一个元素(无论是多少层),另一个不会随着改变。
1 import copy 2 just = ['eric','bob',34,'ida'] 3 dep = ['helo','welcome','jams'] 4 just.append(dep) 5 jesp = copy.deepcopy(just) 6 just[1] = 'tom' 7 jesp[4][0] = 'hi' 8 9 print(just,id(just)) 10 print(jesp,id(jesp)) 11 12 13 14 ['eric', 'tom', 34, 'ida', ['helo', 'welcome', 'jams']] 43071752 15 ['eric', 'bob', 34, 'ida', ['hi', 'welcome', 'jams']] 43348872