深浅拷贝

深浅拷贝

可变类型和比可变类型

值改变,id不变,称为可变类型

值改变,id也改变的称为不可变类型

拷贝

仅加一个变量的引用指向

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = l1

l1.append('g')

print('l1',l1)
print('l2',l2)
l1 ['a', 'b', 'c', ['d', 'e', 'f'], 'g']
l2 ['a', 'b', 'c', ['d', 'e', 'f'], 'g']

浅拷贝

如果原数据中含有引用类型,引用类型改变,拷贝数据也随之发生改变

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.copy(l1)

l1.append('g')

print('l1',l1)
print('l2',l2)

l1[3].append('g')

print('l1',l1)
print('l2',l2)
l1 ['a', 'b', 'c', ['d', 'e', 'f'], 'g']
l2 ['a', 'b', 'c', ['d', 'e', 'f']]
l1 ['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
l2 ['a', 'b', 'c', ['d', 'e', 'f', 'g']]

深拷贝

相当于另开辟了一个新的内存地址,拷贝里所有内容都不会因为原变量改变而改变

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.deepcopy(l1)

l1.append('g')

print('l1',l1)
print('l2',l2)

l1[3].append('g')

print('l1',l1)
print('l2',l2)
l1 ['a', 'b', 'c', ['d', 'e', 'f'], 'g']
l2 ['a', 'b', 'c', ['d', 'e', 'f']]
l1 ['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
l2 ['a', 'b', 'c', ['d', 'e', 'f']]
posted @ 2019-09-16 17:07  Agsol  阅读(95)  评论(0编辑  收藏  举报