Python 的set 类型及其copy方法

原文地址为: Python 的set 类型及其copy方法

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) insertsreferences into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, insertscopies 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. 


转载请注明本文地址: Python 的set 类型及其copy方法

猜你喜欢

转载自blog.csdn.net/hong2511/article/details/80856206
今日推荐