6.Python深浅拷贝
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了6.Python深浅拷贝相关的知识,希望对你有一定的参考价值。
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深浅拷贝的主要内容,如果未能解决你的问题,请参考以下文章