Python深淺拷貝

1、引言

在python中,對象賦值其實是對象的引用。當建立一個對象,而後把它賦給另外一個變量的時候,python並無拷貝這個對象,而只是拷貝了這個對象的引用app

針對該列表l1=['a','b','c',['d','e','f']]通常有三種方法,分別爲:拷貝(賦值)、淺拷貝、深拷貝spa

注意:拷貝/淺拷貝/深拷貝都是針對可變類型數據而言的code

1.一、可變or不可變

id不變值可變,即在原值的基礎上修改,則爲可變數據類型;值變id也變,即從新申請一個空間放入新值,則爲不可變數據類型。對象

age = 19
print(f'first:{id(age)}')
age = 20
print(f'second:{id(age)}')
first:4384901776
second:4384901808

2、拷貝

若是l2是l1的拷貝對象,則l1內部的任何數據類型的元素變化,則l2內部的元素也會跟着改變,由於可變類型值變id不變。it

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = l1

l1.append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']

3、淺拷貝

若是l2是l1的淺拷貝對象,則l1內的不可變元素髮生了改變,l2不變;若是l1內的可變元素髮生了改變,則l2會跟着改變。class

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.copy(l1)

l1.append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]
l1[3].append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f', 'g']]

4、深拷貝


若是l2是l1的深拷貝對象,則l1內的不可變元素髮生了改變,l2不變;若是l1內的可變元素髮生了改變,l2也不會變,即l2永遠不會由於l1的變化而變化。
import

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.deepcopy(l1)

l1.append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]
l1[3].append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]
相關文章
相關標籤/搜索