python深淺拷貝

2022-02-01 06:54:24 字數 2707 閱讀 3559

code

import copy

age = 19

print(f

'first:')

age = 20

print(f

'second:')

l1 = ['

a', '

b', '

c', ['

d', '

e', 'f'

]]l2 =l1

print("*

"*25,"

賦值","

*"*25)'

g')print(

"l1:

",l1)

print(

"l2:

",l2)

l1 = ['

a', '

b', '

c', ['

d', '

e', 'f'

]]l2 =copy.copy(l1)

print("*

"*25,"

淺拷貝-修改不可變元素

","*

"*25)'

g')print(

"l1:

",l1)

print(

"l2:

",l2)

print("*

"*25,"

淺拷貝-修改可變元素

","*

"*25

)l1[g'

)print(

"l1:

",l1)

print(

"l2:

",l2)

l1 = ['

a', '

b', '

c', ['

d', '

e', 'f'

]]l2 =copy.deepcopy(l1)

print("*

"*25,"

深拷貝-修改不可變元素

","*

"*25)'

g')print(

"l1:

",l1)

print(

"l2:

",l2)

print("*

"*25,"

深拷貝-修改可變元素

","*

"*25

)l1[g'

)print(

"l1:

",l1)

print(

"l2:

",l2)

outputs

macname@macdemacbook-pro py %python3 cccccc.py

first:

4525530480

second:

4525530512

************************* 賦值 *************************l1: ['a

', '

b', '

c', ['

d', '

e', '

f'], 'g'

]l2: ['a

', '

b', '

c', ['

d', '

e', '

f'], 'g'

]************************* 淺拷貝-修改不可變元素 *************************l1: ['a

', '

b', '

c', ['

d', '

e', '

f'], 'g'

]l2: ['a

', '

b', '

c', ['

d', '

e', 'f'

]]************************* 淺拷貝-修改可變元素 *************************l1: ['a

', '

b', '

c', ['

d', '

e', '

f', '

g'], 'g'

]l2: ['a

', '

b', '

c', ['

d', '

e', '

f', 'g'

]]************************* 深拷貝-修改不可變元素 *************************l1: ['a

', '

b', '

c', ['

d', '

e', '

f'], 'g'

]l2: ['a

', '

b', '

c', ['

d', '

e', 'f'

]]************************* 深拷貝-修改可變元素 *************************l1: ['a

', '

b', '

c', ['

d', '

e', '

f', '

g'], 'g'

]l2: ['a

', '

b', '

c', ['

d', '

e', 'f'

]]macname@macdemacbook-pro py %

python 深淺拷貝案例 python 深淺拷貝

深淺拷貝 對於 數字 和 字串 而言,賦值 淺拷貝和深拷貝無意義,因為其永遠指向同乙個記憶體位址 import copy a1 22255 a2 22255 print id a1 id a2 3428240 3428240 對於字典 元祖 列表 而言,進行賦值 淺拷貝和深拷貝時,其記憶體位址的變化...

python 深淺拷貝

建立乙個寬度為3,高度為4的陣列 mylist 0 3 4 0,0,0 0,0,0 0,0,0 0,0,0 但是當操作mylist 0 1 1時,發現整個第二列都被賦值,變成 0,1,0 0,1,0 0,1,0 0,1,0 list n n shallow copies of list concat...

python深淺拷貝

python 深淺拷貝 shallow copy 和 deep copy 對於乙個列表,列表裡面可以再放入乙個列表 1 若想複製這乙個列表,使用列表的普通的copy 方法,只能拷貝出列表裡表層的元素,而列表裡的列表卻無法拷貝,只能指向前乙個列表.修改拷貝出的列表裡列表裡的元素,原來的列表會發生改變....