标签:image 技术 重要 int hal ffffff 浅拷贝 技术分享 png
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]
如果觉得好,请点个赞评论鼓励一下作者,谢谢!
标签:image 技术 重要 int hal ffffff 浅拷贝 技术分享 png
原文地址:http://blog.51cto.com/10777193/2070732