Python基础之深浅copy

1. 赋值

```Python 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指向的是同一个内存地址,所以它们是一样的。

<h2>2. 浅copy</h2>
<h3>2.1 示例1</h3>
```Python
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 示例二

```Python lst1 = [1, 2, 3, ["a", "b", "c"]] lst2 = lst1.copy() lst1[0] = 11 print(lst1, id(lst1)) print(lst2, id(lst2)) ``` 执行结果为: ```Python [11, 2, 3, ['a', 'b', 'c']] 48285736 [1, 2, 3, ['a', 'b', 'c']] 48285776 ```

2.3 示例三

```Python lst1 = [1, 2, 3, ["a", "b", "c"]] lst2 = lst1.copy() lst1[3][0] = "d" print(lst1, id(lst1)) print(lst2, id(lst2)) ``` 执行结果为: ```Python [1, 2, 3, ['d', 'b', 'c']] 48285536 [1, 2, 3, ['d', 'b', 'c']] 48285736 ```

2.4 总结

对于浅copy来所,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址。
所以,对于第二层以及更深的层数来说,保持一致性。

3. 深拷贝(deepcopy)

3.1 示例一

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

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

执行结果为:
```Python
[1, 2, 3, ['a', 'b', 'c']] 54249392
[1, 2, 3, ['a', 'b', 'c']] 54249992

3.2 示例二

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

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

执行结果为:
```Python
[11, 2, 3, ['a', 'b', 'c']] 48678832
[1, 2, 3, ['a', 'b', 'c']] 48679432

3.3 示例三

```Python 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))

执行结果为:
```Python
[1, 2, 3, ['d', 'b', 'c']] 46516144
[1, 2, 3, ['a', 'b', 'c']] 46516744

3.4 总结

对于deepcopy来说,两个是完全独立的,改变任意一个的任何元素(无论多少层),另一个绝对不改变。
posted @ 2018-09-11 21:39  _杨魏  阅读(102)  评论(0编辑  收藏  举报