Import Copy
DIC = {#定义一个字典, each element in the dictionary is an array.
"CPU": [80,],
"Mem": [80],
"Disk": [80,]
}
New_dic = Copy.copy (DIC) #浅拷贝, the first-level dictionary is copied and the memory space is reassigned. But the second-level array element address is the same, so change the array value of a dictionary, and the array value of the other dictionary changes.
new_dic[' CPU '][0]=50
Print (ID (DIC))
Print (ID (new_dic))
Print (DIC)
Print (New_dic)
Print (ID (dic["CPU"]))
Print (ID (new_dic["CPU"]))
Output:
4364928
4988880 #浅拷贝 only the first-level dictionary is copied and the memory is reassigned.
{' Disk ': [+], ' CPU ': [[], ' mem ': [80]}
{' Disk ': [+], ' CPU ': [[], ' mem ': [80]}
5890896
5890896 # Shallow Copy the second-level array is not copy and the memory address is not changed.
#如果是深拷贝, the dictionary and the next-level array are copied, and the memory is redistributed
New_dic = Copy.deepcopy (DIC)
new_dic[' CPU '][0]=50
Print (ID (DIC))
Print (ID (new_dic))
Print (DIC)
Print (New_dic)
Print (ID (dic["CPU"]))
Print (ID (new_dic["CPU"]))
Output:
9804416
15901520
{' Disk ': [+], ' CPU ': [+], ' mem ': [80]}
{' Disk ': [+], ' CPU ': [[], ' mem ': [80]}
16245584
16244984 #第二层的数组也重新分配内存, so changing the new_dic data element does not affect the value of the array element of DIC.
For numbers and strings, neither the assignment nor the dark copy will reallocate memory.
Import Copy
A1 = "ASDF"
a3 = A1
A2 = copy.deepcopy (A1)
Print (ID (A1))
Print (ID (A2))
Print (ID (A3))
Output:
2251168 #三个变量的内存地址都一样.
2251168
2251168
Python depth copy