Python的深拷贝与浅拷贝

时间:2021-11-16 22:08:39

Python的深拷贝与浅拷贝

Python中的赋值一般是传递对象的引用,修改一个对象,会导致其他对象也受到改变

python的copy模块提供了拷贝的函数,可以进行浅拷贝和深拷贝

copy模块提供了两个函数:

copy.copy(x) 返回x的浅拷贝,只拷贝x对象,不拷贝x内部的子对象

copy.deepcopy(x) 返回x的深拷贝,拷贝x对象及其子对象

实例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/23 21:05
# @File : copy1.py

#深拷贝与浅拷贝


import copy

sublist = ['a', 'b', 'c']
mylist = list(range(6))
mylist.append(sublist)

shallow_list = copy.copy(mylist)
deep_list = copy.deepcopy(mylist)
print('original ')
print('mylist ', mylist)
print('shallow_list', shallow_list)
print('deep_lis', deep_list)

mylist.append(6)
print("\nmylist append 6")
print('mylist ', mylist)
print('shallow_list', shallow_list)
print('deep_list', deep_list)

sublist.append('d')
print("\nsublist append 'd'")
print('mylist ', mylist)
print('shallow_list', shallow_list)
print('deep_list', deep_list)

输出:

F:\python\python.exe E:/Python工作空间/model/copy/copy1.py
original
('mylist ', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']])
('shallow_list', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']])
('deep_lis', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']])

mylist append 6
('mylist ', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c'], 6])
('shallow_list', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']])
('deep_list', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']])

sublist append 'd'
('mylist ', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c', 'd'], 6])
('shallow_list', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c', 'd']])
('deep_list', [0, 1, 2, 3, 4, 5, ['a', 'b', 'c']])

Process finished with exit code 0

总结

本文介绍了对象的赋值和拷贝,以及它们之间的差异:

Python中对象的赋值都是进行对象引用(内存地址)传递

使用copy.copy(),可以进行对象的浅拷贝,它复制了对象,但对于对象中的元素,依然使用原始的引用

如果需要复制一个容器对象,以及它里面的所有元素(包含元素的子元素),可以使用copy.deepcopy()进行深拷贝

对于非容器类型(如数字、字符串、和其他’原子’类型的对象)没有被拷贝一说

如果元祖变量只包含原子类型对象,则不能深拷贝,看下面的例子