首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python中Set的深浅Copy

Python中Set的深浅Copy

作者头像
用户7886150
修改2021-01-12 14:30:16
修改2021-01-12 14:30:16
6890
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: Python中set的copy

深浅copy 

  1、赋值运算 

  对于赋值运算来说,list1与list2指向的是同一个内存地址,所以他们是完全一样的。 

list1=['Jordan','James','Paul','Jeorage','Curry']

list2=list1

list1.append('Irving')

print(list1) #['Jordan', 'James', 'Paul', 'Jeorage', 'Curry', 'Irving']

print(list2) # #['Jordan', 'James', 'Paul', 'Jeorage', 'Curry', 'Irving'] 

  2、浅拷贝copy 

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

l1 = [1,2,3,['hello','world']]

l2 = l1.copy()

print(l1,id(l1))  # [1, 2, 3, ['hello', 'world']] 1920725366664

print(l2,id(l2))  # [1, 2, 3, ['hello', 'world']] 1920726234696

l1[1] = 222

print(l1,id(l1))  #[1, 222, 3, ['hello', 'world']] 1920725366664

print(l2,id(l2))  # [1, 2, 3, ['hello', 'world']] 1920726234696

l1[3][0] = 'everybody'

print(l1,id(l1[3]))  # [1, 222, 3, ['everybody', 'world']] 1920726234824

print(l2,id(l2[3]))  # [1, 2, 3, ['everybody', 'world']] 1920726234824 

  3、深拷贝deepcopy 

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

import copy

l1 = [1,2,3,['hello','world']]

l2=copy.deepcopy(l1)

print(l1,id(l1))  # [1, 2, 3, ['hello', 'world']] 2200548595592

print(l2,id(l2))  # [1, 2, 3, ['hello', 'world']] 2200548596424

l1[1] = 222

print(l1,id(l1))  #[1, 222, 3, ['hello', 'world']] 2200548595592

print(l2,id(l2))  # [1, 2, 3, ['hello', 'world']] 2200548596424

l1[3][0] = 'everybody'

print(l1,id(l1[3]))  # [1, 222, 3, ['everybody', 'world']] 2200548595400

print(l2,id(l2[3]))  # [1, 2, 3, ['hello', 'world']] 2200548596360 

类似C、C++中指针中

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档