Python数据结构之四——set(集合)
Python版本:3.6.2 操作系统:Windows 作者:SmallWZQ
经过几天的回顾和学习,我终于把Python 3.x中的基础知识介绍好啦。下面将要继续什么呢?让我想想先~~~嗯,还是先整理一下近期有关Python基础知识的随笔吧。
Python编程软件的安装与使用——Windows、Linux和Mac
Python基础——输出[print()]与输入[input()]
上述六篇均为Python 3.x的基础知识。九尺高台,起于累土。学习Python就要从最基本开始,经过逐步的积累,才能有所成就。
Python基础知识再次回顾好了,接下来该干嘛呢?这不继续Python数据结构了吗?
上次我写了有关Python数据结构(列表、元组、字典)的3篇随笔:
本篇随笔将开始一段关于set(集合)之旅吧。
什么是集合呢?
说到集合,我首先想到了高中的数学。高中,人生学习中最繁忙的一段时光。直到现在,我能回忆起最多的就是学习、学习、还是读书……言归正传,高一时的数学,我们就接触到了集合。书中应该是这样定义的:
集合:由一个或多个确定的元素所构成的整体。若x是集合A的元素,则记作x∈A。
集合中的元素有三个特征:
1. 确定性:集合中的元素必须是确定的;
2. 互异性:集合中的元素互不相同,例如:集合A={1,a},则a不能等于1);
3. 无序性:集合中的元素没有先后之分,例如:集合{3,4,5}和{3,5,4}算作同一个集合。
Python 3.x中的set特征与数学中类似。我们之前学过list、tuple以及dict。其实,set与dict大致相同,但set没有Value,只有key。因此,set只是一组key的集合。由于key不能重复,所以,在set中,没有重复的key。
创建集合
1.1 创建空集合
在集合中,创建空集合(set)必须使用函数set()。
#创建空集合
>>>a = set()
>>>a
set()
>>>type(a)
<class 'set'>
注:不能使用{},{}用于创建空字典。
1.2 创建非空集合
非空集合可以用大括号{}或 set()函数来创建。
#创建集合
>>>a={'a','b','c','d'}
>>>b=set('abcdefabcd')
>>>c=set({'a':1,'b':2,'c':3})
>>>d=set(['a','b','c','a'])
#运行结果
>>>print(a,type(a))
{'c', 'd', 'b', 'a'} <class 'set'>
>>>print(b,type(b))
{'f', 'e', 'b', 'c', 'd', 'a'} <class 'set'>
>>>print(c,type(c))
{'b', 'a','c'} <class 'set'>
>>>print(d,type(d))
{'c', 'b', 'a'} <class 'set'>
特别地,set中的元素是无序的,并且重复元素在set中自动被过滤。
#set中重复元素被自动过滤
>>>s = {1,2,,1,2,4,4,3,3}
>>>s
{1,2,3,4}
功能属性
set有很多很多的功能属性。你们不信?不信的话,继续往下看呗~~~
set功能属性如下:
1 class set(object):
2 """
3 set() -> new empty set object
4 set(iterable) -> new set object
5
6 Build an unordered collection of unique elements.
7 """
8 def add(self, *args, **kwargs): # real signature unknown
9 """
10 Add an element to a set.
11
12 This has no effect if the element is already present.
13 """
14 pass
15
16 def clear(self, *args, **kwargs): # real signature unknown
17 """ Remove all elements from this set. """
18 pass
19
20 def copy(self, *args, **kwargs): # real signature unknown
21 """ Return a shallow copy of a set. """
22 pass
23
24 def difference(self, *args, **kwargs): # real signature unknown
25 """
26 Return the difference of two or more sets as a new set.
27
28 (i.e. all elements that are in this set but not the others.)
29 """
30 pass
31
32 def difference_update(self, *args, **kwargs): # real signature unknown
33 """ Remove all elements of another set from this set. """
34 pass
35
36 def discard(self, *args, **kwargs): # real signature unknown
37 """
38 Remove an element from a set if it is a member.
39
40 If the element is not a member, do nothing.
41 """
42 pass
43
44 def intersection(self, *args, **kwargs): # real signature unknown
45 """
46 Return the intersection of two sets as a new set.
47
48 (i.e. all elements that are in both sets.)
49 """
50 pass
51
52 def intersection_update(self, *args, **kwargs): # real signature unknown
53 """ Update a set with the intersection of itself and another. """
54 pass
55
56 def isdisjoint(self, *args, **kwargs): # real signature unknown
57 """ Return True if two sets have a null intersection. """
58 pass
59
60 def issubset(self, *args, **kwargs): # real signature unknown
61 """ Report whether another set contains this set. """
62 pass
63
64 def issuperset(self, *args, **kwargs): # real signature unknown
65 """ Report whether this set contains another set. """
66 pass
67
68 def pop(self, *args, **kwargs): # real signature unknown
69 """
70 Remove and return an arbitrary set element.
71 Raises KeyError if the set is empty.
72 """
73 pass
74
75 def remove(self, *args, **kwargs): # real signature unknown
76 """
77 Remove an element from a set; it must be a member.
78
79 If the element is not a member, raise a KeyError.
80 """
81 pass
82
83 def symmetric_difference(self, *args, **kwargs): # real signature unknown
84 """
85 Return the symmetric difference of two sets as a new set.
86
87 (i.e. all elements that are in exactly one of the sets.)
88 """
89 pass
90
91 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
92 """ Update a set with the symmetric difference of itself and another. """
93 pass
94
95 def union(self, *args, **kwargs): # real signature unknown
96 """
97 Return the union of sets as a new set.
98
99 (i.e. all elements that are in either set.)
100 """
101 pass
102
103 def update(self, *args, **kwargs): # real signature unknown
104 """ Update a set with the union of itself and others. """
105 pass
106
107 def __and__(self, *args, **kwargs): # real signature unknown
108 """ Return self&value. """
109 pass
110
111 def __contains__(self, y): # real signature unknown; restored from __doc__
112 """ x.__contains__(y) <==> y in x. """
113 pass
114
115 def __eq__(self, *args, **kwargs): # real signature unknown
116 """ Return self==value. """
117 pass
118
119 def __getattribute__(self, *args, **kwargs): # real signature unknown
120 """ Return getattr(self, name). """
121 pass
122
123 def __ge__(self, *args, **kwargs): # real signature unknown
124 """ Return self>=value. """
125 pass
126
127 def __gt__(self, *args, **kwargs): # real signature unknown
128 """ Return self>value. """
129 pass
130
131 def __iand__(self, *args, **kwargs): # real signature unknown
132 """ Return self&=value. """
133 pass
134
135 def __init__(self, seq=()): # known special case of set.__init__
136 """
137 set() -> new empty set object
138 set(iterable) -> new set object
139
140 Build an unordered collection of unique elements.
141 # (copied from class doc)
142 """
143 pass
144
145 def __ior__(self, *args, **kwargs): # real signature unknown
146 """ Return self|=value. """
147 pass
148
149 def __isub__(self, *args, **kwargs): # real signature unknown
150 """ Return self-=value. """
151 pass
152
153 def __iter__(self, *args, **kwargs): # real signature unknown
154 """ Implement iter(self). """
155 pass
156
157 def __ixor__(self, *args, **kwargs): # real signature unknown
158 """ Return self^=value. """
159 pass
160
161 def __len__(self, *args, **kwargs): # real signature unknown
162 """ Return len(self). """
163 pass
164
165 def __le__(self, *args, **kwargs): # real signature unknown
166 """ Return self<=value. """
167 pass
168
169 def __lt__(self, *args, **kwargs): # real signature unknown
170 """ Return self<value. """
171 pass
172
173 @staticmethod # known case of __new__
174 def __new__(*args, **kwargs): # real signature unknown
175 """ Create and return a new object. See help(type) for accurate signature. """
176 pass
177
178 def __ne__(self, *args, **kwargs): # real signature unknown
179 """ Return self!=value. """
180 pass
181
182 def __or__(self, *args, **kwargs): # real signature unknown
183 """ Return self|value. """
184 pass
185
186 def __rand__(self, *args, **kwargs): # real signature unknown
187 """ Return value&self. """
188 pass
189
190 def __reduce__(self, *args, **kwargs): # real signature unknown
191 """ Return state information for pickling. """
192 pass
193
194 def __repr__(self, *args, **kwargs): # real signature unknown
195 """ Return repr(self). """
196 pass
197
198 def __ror__(self, *args, **kwargs): # real signature unknown
199 """ Return value|self. """
200 pass
201
202 def __rsub__(self, *args, **kwargs): # real signature unknown
203 """ Return value-self. """
204 pass
205
206 def __rxor__(self, *args, **kwargs): # real signature unknown
207 """ Return value^self. """
208 pass
209
210 def __sizeof__(self): # real signature unknown; restored from __doc__
211 """ S.__sizeof__() -> size of S in memory, in bytes """
212 pass
213
214 def __sub__(self, *args, **kwargs): # real signature unknown
215 """ Return self-value. """
216 pass
217
218 def __xor__(self, *args, **kwargs): # real signature unknown
219 """ Return self^value. """
220 pass
221
222 __hash__ = None
set
set功能属性虽多,但平时常用的也就那么几个。
常用属性
1. 添加元素
在集合中添加元素,可以使用add()方法,并且不生成一个新的集合。
#添加元素:add()
>>>s = {1,2,3}
>>>s.add(4)
>>>s
{1,2,3,4}
>>>s.add('g')
>>>s
{1,2,3,4,'g'}
>>>s.add(4)
>>>s
{1,2,3,4,'g'}
add()方法可以向set中添加元素,可以重复添加,但不会有效果。
2. 删除元素
set中利用remove()方法可以删除集合中的元素。
#删除元素
>>>s
{1,2,3,4,'g'}
>>>s.remove('g')
>>>s
{1,2,3,4}
3. 清空元素
clear()方法可以清空set中的元素。
#清空元素
>>>a = {1,2,3,4}
>>>b = a.clear()
>>>print(a,type(a))
set() <class 'set'>
>>>print(b,type(b))
None <class 'NoneType'>
4. 复制元素
copy()方法只能浅拷贝set中的元素,并生成一个新的集合。
#浅拷贝:copy()
>>>a = {1,(9,2),3}
>>>b = a.copy()
>>>print(a,id(a))
{(9, 2), 1, 3} 2097937619880
>>>print(b,id(b))
{(9, 2), 1, 3} 2097937620776 #赋值
>>>s = {1,2,3,4}
>>>d = s
>>>print(s,id(s))
{1, 2, 3, 4} 2097937785128
>>>print(d,id(d))
{1, 2, 3, 4} 2097937785128
5. pop()
pop()方法用于从set中随机取一个元素。记住,是随机的~~~
#pop()方法
>>>s = {1,2,3,4,5,'g','s'}
>>>s.pop()
'g'
>>>s.pop()
3
6. set集合操作
set与数学中的集合类似,是无序的和无重复元素的集合。因此,在Python中,set可以进行交集、并集、补集等操作。
| 数学符号 | Python符号 | 含义 |
| - 或\ | - | 差集,相对补集 |
| ∩ | & | 交集 |
| ∪ | | | 并集 |
| ≠ | != | 不等于 |
| = | == | 等于 |
| ∈ | in | 是成员关系 |
| ∉ | not in | 非成员关系 |
#set集合操作
>>>s = {1,2,3,4}
>>>d = {2.3.5.6}
>>>s & d
{2.3}
>>>s | d
{1,2,3,4,5,6}
>>>s - d
{1,4}
>>>d - s
{5,6}
set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。因此,最常用的key是字符串。
“思想者”
set中存储着key,集合中不能放入可变的对象。之前的文章也说过:tuple是不可变的,而list是可变的。因此,set中是可以存储tuple的。这是真的吗?
时间是检验真理的唯一标准。下面请看示例代码:
#tuple可以作为集合中的元素
>>>s = {(1,),(1,2,3),1,2,'g'}
>>>s
{(1,),(1,2,3),1,2,'g'} #tuple也有失灵的时候
>>>t = (1,2,[1,2,3],4)
>>>type(t)
<class 'tuple'>
>>>d = {1,2,(1,2,[1,2,3],4)}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
为什么会有错误呢?我也不清楚哎~~~这里面的道道很深,请读者细细体会。
set是一种数据结构。如果要详细的介绍set,我应该可以去出书了。这篇随笔只是起到入门的效果。
正所谓“师傅”领进门,修行靠大家嘛!
Python数据结构之四——set(集合)的更多相关文章
- python数据结构元组与集合
元组 1.()来定义 2.有序,同列表 3.元组一旦创建,不能被修改 注:元组的标识是逗号,不是括号 元组的定义 a = (1,2) type(a) <class 'tuple'> 元组的 ...
- 【Python学习之四】集合类型
环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 python3.6 一.字符串:字符串实际上就是字符的数组1.切片是指 ...
- Python数据结构与算法--算法分析
在计算机科学中,算法分析(Analysis of algorithm)是分析执行一个给定算法需要消耗的计算资源数量(例如计算时间,存储器使用等)的过程.算法的效率或复杂度在理论上表示为一个函数.其定义 ...
- Python数据结构与算法--数据类型
从数据类型开始 Python支持面向对象的编程范式,这意味着Python把数据看成解决问题的关键. 在Python中,类似其他的面向对象的编程语言, 我们定义一个类,用来描述数据是什么 (状态) 和数 ...
- python数据结构之树和二叉树(先序遍历、中序遍历和后序遍历)
python数据结构之树和二叉树(先序遍历.中序遍历和后序遍历) 树 树是\(n\)(\(n\ge 0\))个结点的有限集.在任意一棵非空树中,有且只有一个根结点. 二叉树是有限个元素的集合,该集合或 ...
- Python学习【第2篇】:Python数据结构
Python数据结构 1.数字类型 2.字符串 3.列表 4.元组 5.字典 6.集合
- Python - 数据结构 - 第十五天
Python 数据结构 本章节我们主要结合前面所学的知识点来介绍Python数据结构. 列表 Python中列表是可变的,这是它区别于字符串和元组的最重要的特点,一句话概括即:列表可以修改,而字符串和 ...
- Python数据结构汇总
Python数据结构汇总 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.线性数据结构 1>.列表(List) 在内存空间中是连续地址,查询速度快,修改也快,但不利于频繁新 ...
- Python 数据结构理解分享
摘要:分享学习Python数据结构的一些理解,主要包含序列(如列表和元组),映射(如字典)以及集合3中基本的数据结构,以及可变和不可变数据类型. Python 中的数据结构是根据某种方式将数据元素组合 ...
随机推荐
- win7 使用anaconda安装tensorflow并且在jupyter notebook上启动
记录一下学习深度学习的小事情: 1.tensorflow 现在只支持windows 64位系统: 2.因为实验室的电脑比较老旧,Gpu配置低,所以选择安装的是tensorflow Cpu版本,对于学习 ...
- linux nvme的那些workqueue
目前nvme三个常见的使用的workqueue ,主要有nvme_workq,nvme_rdma_wq ,nvme_fc_wq,下面一一描述一下初始化及使用的场景.分别对应于NVME over PCI ...
- Java this 关键字的用法
this 关键字的用法 this 在类中就是代表当前对象,可以通过 this 关键字完成当前 对象的成员属性.成员方法和构造方法的调用. 那么何时用 this? 当在定义类中的方法时,如果需要调用该类 ...
- RocketMQ-消费重试机制
介绍: RocketMQ的消息重试及时分为两种,一种是Producer端重试,一种是Consume端重试. 1.Producer端重试 : 1.1消息发没发成功,默认情况下是3次重试. 2.Consu ...
- Log4j源码解析--Layout类解析
本文转载上善若水的博客,原文出处:http://www.blogjava.net/DLevin/archive/2012/07/04/382131.html.感谢作者的分享. Layout负责将Log ...
- Linux指令--chown
chown将指定文件的拥有者改为指定的用户或组,用户可以是用户名或者用户ID:组可以是组名或者组ID:文件是以空格分开的要改变权限的文件列表,支持通配符.系统管理员经常使用chown命令,在将文件拷贝 ...
- Android开发——打造简单的Viewpager指示器
准备工作: 1.两张不同颜色的小圆点图片,可以去阿里巴巴矢量图网站搜索 我把我使用的图片贴出来 2.一个简单的Viewpager的实现 下面是简单的Viewpager实现步骤: 1.布局文件使用Vie ...
- DDMS和程序打包过程
1. Android版本对应api级别 2.3~~~~~10 3.0~~~~~11 4.0~~~~~14 4.1.2~~~16 2.3和4.1.2是最稳定的 2.Android手机常见分辨率 320* ...
- ResultSet详细
1. ResultSet细节1功能:封锁结果集数据操作:如何获得(取出)结果 package com.sjx.a; import java.sql.Connection; import java.sq ...
- 浅谈最大流的Dinic算法
PART 1 什么是网络流 网络流(network-flows)是一种类比水流的解决问题方法,与线性规划密切相关.网络流的理论和应用在不断发展,出现了具有增益的流.多终端流.多商品流以及网络流的分解与 ...