Python 的set 类型及其copy方法

本文详细介绍了 Python 中 set 类型的使用方法,包括创建、排序等基本操作,并通过实例对比了浅复制与深复制的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 的set 类型

  1. 用法

>>> set('you need python.')

{' ', 'd', 'e', 'o', 'h', 'p', '.', 'n', 'y', 'u', 't'}

 

>>> type(set('you need python.'))

<class 'set'>

 

>>> sorted(set('you need python.'))

[' ', '.', 'd', 'e', 'h', 'n', 'o', 'p', 't', 'u', 'y']

 

>>> type(sorted(set('you need python.')))

<class 'list'>

 

  1. copy() 方法

set 有一个copy方法,定义是Return a new set with ashallow copy.

假设有一个set结构的变量sa, 调用set的copy方法并把结果赋给sb, 再调用set的pop方法从sb中取出一个值,类似于对栈的出栈操作。

sa=set('you need python.')

sb=sa.copy()

sb.pop()

之后再查看sa,sb的值,结果sa的值没有改变,而sb的值少了一个。说明对sb的改变并不会影响sa。

>>> sa

{'u', 'h', 'e', 'y', 'p', '.', ' ', 'n', 't', 'o', 'd'}

>>> sb

{'h', 'e', 'y', 'p', '.', ' ', 'n', 't', 'o', 'd'}

 

我的疑问是为什么官方文档中对copy方法的描述是 shallow copy?

在我的理解中,如果是shallowcopy的话, 并不会为sb 变量新分配一片内存,相当于把sb指向sa变量所在的内存区域。这样如果对sb做任何改动,实际上影响到了sa. 但上面的测试结果并非如此。

 

从Python 官方文档中找到如下描述:

The differencebetween shallow and deep copying is only relevant forcompound objects (objects that contain other objects, like lists or classinstances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

 

用一个嵌套的list进行测试:

a=[1,2,[3,4]]

b=a.copy()

b[2]=[5,6]

只对b的值做修改,完成后查看a,b的值,分别是

>>> a

[1, 2, [3, 4]]

>>> b

[1, 2, [5, 6]]

证明,仍然是deepcopy. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值