Python基础之深浅copy

2021-07-02 11:06

阅读:487

标签:import   int   一致性   3.3   3.1   2.4   print   赋值   执行   

1. 赋值

lst1 = [1, 2, 3, ["a", "b", "c"]]
lst2 = lst1

lst1[0] = 11
print(lst1)         #[11, 2, 3, [‘a‘, ‘b‘, ‘c‘]]
print(lst2)         #[11, 2, 3, [‘a‘, ‘b‘, ‘c‘]]

lst1[3][0] = "d"
print(lst1)         #[11, 2, 3, [‘d‘, ‘b‘, ‘c‘]]
print(lst2)         #[11, 2, 3, [‘d‘, ‘b‘, ‘c‘]]

对于赋值运算来说,lst1和lst2指向的是同一个内存地址,所以它们是一样的。

2. 浅copy

2.1 示例1

lst1 = [1, 2, 3, ["a", "b", "c"]]
lst2 = lst1.copy()
print(lst1, id(lst1))
print(lst2, id(lst2))

执行结果为:

[1, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 48285736
[1, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 48285776

2.2 示例二

lst1 = [1, 2, 3, ["a", "b", "c"]]
lst2 = lst1.copy()
lst1[0] = 11
print(lst1, id(lst1))
print(lst2, id(lst2))

执行结果为:

[11, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 48285736
[1, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 48285776

2.3 示例三

lst1 = [1, 2, 3, ["a", "b", "c"]]
lst2 = lst1.copy()
lst1[3][0] = "d"
print(lst1, id(lst1))
print(lst2, id(lst2))

执行结果为:

[1, 2, 3, [‘d‘, ‘b‘, ‘c‘]] 48285536
[1, 2, 3, [‘d‘, ‘b‘, ‘c‘]] 48285736

2.4 总结

对于浅copy来所,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址。

所以,对于第二层以及更深的层数来说,保持一致性。

3. 深拷贝(deepcopy)

3.1 示例一

import copy
lst1 = [1, 2, 3, ["a", "b", "c"]]
lst2 = copy.deepcopy(lst1)

print(lst1, id(lst1))
print(lst2, id(lst2))

执行结果为:

[1, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 54249392
[1, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 54249992

3.2 示例二

import copy
lst1 = [1, 2, 3, ["a", "b", "c"]]
lst2 = copy.deepcopy(lst1)

lst1[0] = 11
print(lst1, id(lst1))
print(lst2, id(lst2))

执行结果为:

[11, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 48678832
[1, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 48679432

3.3 示例三

import copy
lst1 = [1, 2, 3, ["a", "b", "c"]]
lst2 = copy.deepcopy(lst1)

lst1[3][0] = "d"
print(lst1, id(lst1))
print(lst2, id(lst2))

执行结果为:

[1, 2, 3, [‘d‘, ‘b‘, ‘c‘]] 46516144
[1, 2, 3, [‘a‘, ‘b‘, ‘c‘]] 46516744

3.4 总结

对于deepcopy来说,两个是完全独立的,改变任意一个的任何元素(无论多少层),另一个绝对不改变。

Python基础之深浅copy

标签:import   int   一致性   3.3   3.1   2.4   print   赋值   执行   

原文地址:https://www.cnblogs.com/yang-wei/p/9630540.html


评论


亲,登录后才可以留言!