浅copy
首先我们来看下面一段代码:
1 1 >>> names = ["maqing"," peilin"," xiaoming"," lilei"," hanmeimei",["maqing","wangchuan","lilong"]] 2 2 >>> names2 = names.copy() 3 3 >>> print(names) 4 4 [‘maqing‘, ‘ peilin‘, ‘ xiaoming‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘lilong‘]] 5 5 >>> names[2] = "小明" 6 7 >>> print(names) 7 8 [‘maqing‘, ‘ peilin‘, ‘小明‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘lilong‘]] 8 9 >>> print(names2) 9 10 [‘maqing‘, ‘ peilin‘, ‘ xiaoming‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘lilong‘]] 10 11 >>> names[-1][2] = "李龙" 11 12 >>> print(names) 12 13 [‘maqing‘, ‘ peilin‘, ‘小明‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘李龙‘]] 13 14 >>> print(names2) 14 15 [‘maqing‘, ‘ peilin‘, ‘ xiaoming‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘李龙‘]]
第一步:修改names中‘xiaoming‘的值为中文"小明",输出列表发现只有names中修改了,但names2中没有修改,符合copy的性质。
第二步:修改names中二级列表"lilong"的值为"李龙",输出names和names2,我们发现‘lilong‘的值都改为中文了,貌似这不符合copy的性质。
这种copy我们称之为浅copy
浅copy的方法有三种:
- 使用切片[:]操作
- 使用工厂函数(如list/dir/set)
- 使用copy模块中的copy()函数
1 person = [‘name‘,[‘saving‘,100]] 2 p1 = copy.copy(person) 3 p2 = person[:] 4 p3 = list(person)
深copy
1 >>> import copy 2 >>> names = ["Will", 28, ["Python", "C#", "JavaScript"]] 3 >>> names2 = copy.deepcopy(names) 4 >>> names[1] = ‘27‘ 5 >>> print(names) 6 [‘Will‘, ‘27‘, [‘Python‘, ‘C#‘, ‘JavaScript‘]] 7 >>> print(names2) 8 [‘Will‘, 28, [‘Python‘, ‘C#‘, ‘JavaScript‘]] 9 >>> names[2][1] = "Ruby" 10 >>> print(names) 11 [‘Will‘, ‘27‘, [‘Python‘, ‘Ruby‘, ‘JavaScript‘]] 12 >>> print(names2) 13 [‘Will‘, 28, [‘Python‘, ‘C#‘, ‘JavaScript‘]]
总结
本文介绍了对象的赋值和拷贝,以及它们之间的差异:
- Python中对象的赋值都是进行对象引用(内存地址)传递
- 使用copy.copy(),可以进行对象的浅拷贝,它复制了对象,但对于对象中的元素,依然使用原始的引用.
- 如果需要复制一个容器对象,以及它里面的所有元素(包含元素的子元素),可以使用copy.deepcopy()进行深拷贝
- 对于非容器类型(如数字、字符串、和其他’原子’类型的对象)没有被拷贝一说
- 如果元祖变量只包含原子类型对象,则不能深拷贝,看下面的例子
时间: 2024-10-29 04:11:11