python基礎之深淺拷貝

2022-08-27 18:18:11 字數 3138 閱讀 3255

深淺拷貝:

對於字串(str),數字(int),布林型別(bool)等型別深淺拷貝都是開闢新記憶體

對於列表(list),集合(set),字典(dict)深淺拷貝可變型別都一樣,如[1,2,3]

對於列表(list),集合(set),字典(dict)存在巢狀的深淺拷貝不一樣,如[1,2,3,[4,5,6]],淺拷貝只拷貝[1,2,3],深拷貝[1,2,3,[4,5,6]]

淺拷貝:拷貝第一層

深拷貝:拷貝所有資料(可變)

應該每次都拷貝乙份(但由於小資料池,未拷貝)

v = 'sundy'

import copy

v1 = copy.copy(v)

v2 =copy.deepcopy(v)

print(id(v),id(v1))

print(id(v),id(v2))

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

1761132524464 1761132524464

1761132524464 1761132524464

v = [1,2,3,4]

import copy

v1 = copy.copy(v)

v2 =copy.deepcopy(v)

print(id(v),id(v1))

print(id(v),id(v2))

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

2561119066504 2561120559432

2561119066504 256112055962

淺拷貝:

v = [1,2,3,4,[5,6,7]]

import copy

v1 = copy.copy(v)

print(v == v1)

print(v is v1)

print(v[4] == v1[4])

print(v[4] is v1[4])

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

true

false

true

true

v = [1,2,3,4,[5,6,7]]

import copy

v1 = copy.copy(v) #淺拷貝只拷貝空殼

print(id(v),id(v1))

print(id(v[2]),id(v1[2]))

print(id(v[4]),id(v1[4]))

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

1978756340040 1978757833096

1689026736 1689026736

1978756340104 1978756340104

#深拷貝

v = [1,2,3,4,[5,6,7]]

import copy

v1 = copy.deepcopy(v)

print(v == v1)

print(v is v1)

print(v[4] == v1[4])

print(v[4] is v1[4])

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

true

false

true

false

v2 =copy.deepcopy(v)#深拷貝拷貝巢狀裡面空殼(即可變型別)

print(id(v),id(v2))

print(id(v[2]),id(v2[2]))

print(id(v[4]),id(v2[4]))

print(id(v[4][1]),id(v2[4][1]))

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

2764609460552 2764610953608

1692303536 1692303536

2764609460616 2764609460616

2764609460552 2764610953800

1692303536 1692303536

2764609460616 2764610955080

1692303632 1692303632

特殊情況

對於不可變型別的元組深淺拷貝記憶體位址不變

v = (1,2,3,4,5)

import copy

v1 = copy.copy(v)

print(id(v),id(v1))

v1 = copy.deepcopy(v)

print(id(v),id(v1))

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

1747241185792 1747241185792

1747241185792 1747241185792

對於不可變型別的元組存在可變型別深拷貝記憶體位址不一樣

v = (1,2,3,4,5,[6,7,8,9])

import copy

v1 = copy.copy(v)

print(id(v),id(v1))

v1 = copy.deepcopy(v)

print(id(v),id(v1))

d:\python3.6\python3.6.exe d:/python_code/day01/day06.py

2430290597736 2430290597736

2430290597736 2430291562760

總結

不可變型別:數字(int),字串(str),布林(bool),元組(tuple)

可變型別:列表(list),字典(dict),集合(set)

深淺拷貝只拷貝可變型別的記憶體位址

python基礎高階之深淺拷貝

深拷貝與淺拷貝的區別 淺複製shadow copy 1,只拷貝物件自身,僅僅是指向被複製的記憶體位址 2,內層列表的引用沒有拷貝,即淺拷貝拷貝的是第一層引用 3,如果原位址中物件被改變了,那麼淺複製出來的物件也會相應改變。深複製deep copy 1,開闢了一塊新的記憶體位址用於存放複製的物件 2,...

Python基礎 深淺拷貝

import copy num 0 copy num copy.copy num print these are normal copy center 60,print num,id num print copy num,id copy num print these are deep copy c...

python之深淺拷貝

lis 1 3,world 1,hello lis 2 lis 1.copy print 列表1元素的id lis 1,id lis 1 0 id lis 1 0 0 id lis 1 0 1 id lis 1 1 id lis 1 2 print 列表2元素的id lis 2,id lis 2 0...