1. 程式人生 > >賦值、淺拷貝以及深拷貝的區別

賦值、淺拷貝以及深拷貝的區別

fff 情況 spa clas nbsp tro 淺拷貝 pen pan

字符串賦值

>>>
>>> str1 = ‘standby‘
>>> 
>>> str2 = str1
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

補充

>>> 
>>> a = ‘standby‘
>>> b = ‘standby‘
>>> 
>>> a == b
True
>>> a is b
True
>>> 
>>> id(a)
139792206350496
>>> id(b)
139792206350496
>>> 

字符串淺拷貝方式一

>>> 
>>> import copy
>>> str1 = ‘standby‘
>>> 
>>> str2 = copy.copy(str1)
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

字符串淺拷貝方式二

>>> 
>>> str1 = ‘standby‘
>>> 
>>> str2 = str1[:]
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

字符串深拷貝

>>> 
>>> import copy
>>> str1 = ‘standby‘
>>> 
>>> str2 = copy.deepcopy(str1)
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

列表賦值

>>> 
>>> list1 = [1, 2, [1, 2]]
>>> 
>>> list2 = list1
>>> 
>>> print list1==list2, list1 is list2
True True
>>> 
>>> id(list1)
139792206344992
>>> id(list2)
139792206344992
>>> 

補充

>>> 
>>> list1 = [1, 2, [‘a‘, ‘c‘]]
>>> list2 = [1, 2, [‘a‘, ‘c‘]]
>>> 
>>> list1 == list2
True
>>> list1 is list2
False
>>> 
>>> id(list1)
139792206356704
>>> id(list2)
139792206348088
>>> 

列表淺拷貝方式一

>>> 
>>> import copy
>>> list1 = [1, 2, [1, 2]]
>>> 
>>> list2 = copy.copy(list1)
>>> 
>>> print list1==list2, list1 is list2
True False
>>> 
>>> 
>>> id(list1)
139792206344920
>>> id(list2)
139792206356560
>>> 

列表淺拷貝方式二

>>> 
>>> list1 = [1, 2, [1, 2]]
>>> 
>>> list2 = list1[:]
>>> 
>>> print list1==list2, list1 is list2
True False
>>> 
>>> id(list1)
139792206356704
>>> id(list2)
139792206344992
>>> 

  

列表深拷貝

>>> 
>>> import copy
>>> list1 = [1, 2, 3, 4]
>>> 
>>> list2 = copy.deepcopy(list1)
>>> 
>>> print list1==list2, list1 is list2
True False
>>> 
>>> id(list1)
139792206344992
>>> id(list2)
139792206344920
>>> 

淺拷貝情況下的修改

>>> 
>>> import copy
>>> list1 = [1, 2, [‘a‘, ‘c‘]]
>>> 
>>> list2 = copy.copy(list1)
>>> print list1==list2, list1 is list2
True False
>>> id(list1)
139792206358720
>>> id(list2)
139792206359080
>>> 
>>> list2[2].append(‘k‘)
>>> print list2,list1
[1, 2, [‘a‘, ‘c‘, ‘k‘]] [1, 2, [‘a‘, ‘c‘, ‘k‘]]
>>> id(list1)
139792206358720
>>> id(list2)
139792206359080
>>> 

  

深拷貝情況下的修改

>>> 
>>> import copy
>>> list1 = [1, 2, [‘a‘, ‘c‘]]
>>> 
>>> list2 = copy.deepcopy(list1)
>>> print list1==list2, list1 is list2
True False
>>> id(list1)
139792206344920
>>> id(list2)
139792206358720
>>> 
>>> list2[2].append(‘k‘)
>>> print list2,list1
[1, 2, [‘a‘, ‘c‘, ‘k‘]] [1, 2, [‘a‘, ‘c‘]]
>>> id(list1)
139792206344920
>>> id(list2)
139792206358720
>>> 

  

 

賦值、淺拷貝以及深拷貝的區別