当前位置:网站首页>Depth copy

Depth copy

2022-06-12 02:20:00 Shallow water carp

shallow copy

shallow copy Is that the memory points differently , Elements id Still use copy Previous , Variable and immutable are the same

1、 shallow copy A list is two lists ,id inequality

s1=[1,2,3,[11,22,33]]
s2=s1.copy()
s1.append(44)
print(s1,id(s1))#[1, 2, 3, [11, 22, 33], 44] 2090904676608
print(s2,id(s2))#[1, 2, 3, [11, 22, 33]] 2090907589440

2、 shallow copy The elements are the same ,id identical

s1=[1,2,3,[11,22,33]]
s2=s1.copy()
s1[-1].append(44)
print(s1,id(s1[-1]))#[1, 2, 3, [11, 22, 33, 44]] 2523862516992
print(s2,id(s2[-1]))#[1, 2, 3, [11, 22, 33, 44]] 2523862516992
# Opened up a new memory space ( Slot position ), Yes s1 Of copy Is a new slot , But the content still uses the previous address , So the list id Different , Elements id identical , In the slot is the memory number , Point to the same list 

3、 Only the memory direction is changed

s1=[1,2,3,[11,22,33]]
s2=s1.copy()
s1[1]=12
print(s1,id(s1[1]))
#[1, 12, 3, [11, 22, 33]] 1960098163344
print(s2,id(s2[1]))
#[1, 2, 3, [11, 22, 33]] 1960098163024

4、 Another way of writing

import copy
s1=[1,2,3,[11,22,33]]
s2=copy.copy(s1)# shallow copy
print(s1,id(s1))#[1, 2, 3, [11, 22, 33]] 2537390491456
print(s2,id(s2))#[1, 2, 3, [11, 22, 33]] 2537393081856
print(s1 is s2)#False
print(id(s1[-1]))#2537393078336
print(id(s2[-1]))#2537393078336

deep copy

deep copy There are two tables , Elements id Different , however python Made an optimization ,python Keep immutable data types in the same , Point to the original copy Previous , Variable re creation , Include tuples

1、copy A list is two lists ,id inequality , Elemental id It's not the same

import copy
s1=[1,2,3,[11,22,33]]
s2=copy.deepcopy(s1)# deep copy
# s1[-1].append(666)
print(s1,id(s1))#[1, 2, 3, [11, 22, 33]] 3071881397824
print(s2,id(s2))#[1, 2, 3, [11, 22, 33]] 3071883988544
print(id(s1[-1]))#2435381575744
print(id(s2[-1]))#2435381576832

2、 Elemental id Dissimilarity , Not shared

import copy
s1=[1,2,3,[11,22,33]]
s2=copy.deepcopy(s1)# deep copy
s1[-1].append(666)
print(s1,id(s1[-1]))
#[1, 2, 3, [11, 22, 33, 666]] 2755944955968
print(s2,id(s2[-1]))
#[1, 2, 3, [11, 22, 33]] 2755944956992

3、 Optimize :python To deep copy Made an optimization , Keep immutable data types in the same , Point to the original copy Previous , Variable re creation , Include tuples
immutable :str、bool、int、tuple
variable :list、dict、set

import copy
s1=[1,2,3,[11,22,33]]
s2=copy.deepcopy(s1)
print(s1,id(s1[1]))#[1, 2, 3, [11, 22, 33]] 1924667763024
print(s2,id(s2[1]))#[1, 2, 3, [11, 22, 33]] 1924667763024
print(id(s1[-1]))#1924675977024
print(id(s2[-1]))#1924675978176
原网站

版权声明
本文为[Shallow water carp]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011151398684.html