1. 程式人生 > >6.Python深淺拷貝

6.Python深淺拷貝

str2 cto str sha ges mage process text pre

Python深淺拷貝

變量賦值的過程:
技術分享圖片

# -*-coding:utf-8 -*-
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘shallowcopy_deepcopy‘

#當拷貝數據足夠多的時候,浪費空間
# str1=[1,"jiaxin","john"]
# str2=[1,"jiaxin","john"]
# print(str1)
# print(str2)

copy方法

str1=[1,"jiaxin","john"]
str2=str1.copy()
print(str1)
print(str2)
# [1, ‘jiaxin‘, ‘john‘]
# [1, ‘jiaxin‘, ‘john‘]

str2[0]=10;
print(str1)
print(str2)
# [1, ‘jiaxin‘, ‘john‘]
# [10, ‘jiaxin‘, ‘john‘]
str3=[[1,2],"jiaxin",‘john‘]
str4=str3.copy()
print(str4)
#[[1, 2], ‘jiaxin‘, ‘john‘]
str4[1]="jiaxin01"
print(str3)     #str3不變,str4改變
print(str4)
# [[1, 2], ‘jiaxin‘, ‘john‘]
# [[1, 2], ‘jiaxin01‘, ‘john‘]


淺拷貝:

技術分享圖片

str5=[[1,2],"jiaxin",‘john‘]
str6=str5.copy()   #等價於str6=str5[:],但是不等於str6=str5  很重要!!!!
print(str5)
print(id(str5[0]))
print(str6)
print(id(str6[0]))
# [[1, 2], ‘jiaxin‘, ‘john‘]
# [[1, 2], ‘jiaxin‘, ‘john‘]
str6[0][1]=201    #str5,str6一起改變
print(str5)
print(str6)
# [[1, 201], ‘jiaxin‘, ‘john‘]
# [[1, 201], ‘jiaxin‘, ‘john‘]

深拷貝
技術分享圖片

# -*-coding:utf-8 -*-
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘deep_copy‘

import copy

#深拷貝需要一個獨立的模塊來完成
a=[[1,2],3,4]
b=copy.deepcopy(a)
print(id(a))
print(id(b))

b[0][0]=99
print(a)
print(b)

#1080515447944
#1080515539400
# [[1, 2], 3, 4]
# [[99, 2], 3, 4]

完全賦值:
B=a情況
技術分享圖片

a=[[1,2],3,4]
b=a
print(id(a))
print(id(b))
b[0][0]=99
print(id(a))
print(id(b))
print(a)
print(b)

# 818876113416
# 818876113416
# 818876113416
# 818876113416
# [[99, 2], 3, 4]
# [[99, 2], 3, 4]

如果覺得好,請點個贊評論鼓勵一下作者,謝謝!

6.Python深淺拷貝