Python 的set 类型及其copy方法
2015-09-24 17:54
736 查看
Python 的set 类型
用法
copy() 方法
set 有一个copy方法,定义是Return a new set with ashallow copy.
假设有一个set结构的变量sa, 调用set的copy方法并把结果赋给sb, 再调用set的pop方法从sb中取出一个值,类似于对栈的出栈操作。
之后再查看sa,sb的值,结果sa的值没有改变,而sb的值少了一个。说明对sb的改变并不会影响sa。
我的疑问是为什么官方文档中对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进行测试:
只对b的值做修改,完成后查看a,b的值,分别是
证明,仍然是deepcopy.
用法
>>> 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'> |
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 {'u', 'h', 'e', 'y', 'p', '.', ' ', 'n', 't', 'o', 'd'} >>> sb {'h', 'e', 'y', 'p', '.', ' ', 'n', 't', 'o', 'd'} |
在我的理解中,如果是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] |
>>> a [1, 2, [3, 4]] >>> b [1, 2, [5, 6]] |
相关文章推荐
- 一个另类的排序——睡排序
- Head First Python学习笔记2——文件与异常
- <think python>一些练习的答案
- Python操作PDF与Tiff文件
- Python Map 并行
- Create a simple REST web service with Python--转载
- python模块imghdr读图片后缀名
- 初学python
- 使用python 的paramiko制作堡垒机
- python matplotlib模块——绘制三维图形、三维数据散点图
- Python 3 抓取网页资源的 N 种方法
- 你可能不知道的python
- Python程序提示SyntaxError: invalid syntax错误
- Python爬取百度贴吧图片
- python:列表推导式,list comprehension
- python处理json
- [LeetCode]题解(python):018-4Sum
- Python 通过print_lol将数据保存到文件中
- python socket编程之select
- Json概述以及python对json的相关操作