Python数据结构之四——set(集合)

  Python版本:3.6.2  操作系统:Windows  作者:SmallWZQ

  经过几天的回顾和学习,我终于把Python 3.x中的基础知识介绍好啦。下面将要继续什么呢?让我想想先~~~嗯,还是先整理一下近期有关Python基础知识的随笔吧。

  Python编程软件的安装与使用——Windows、Linux和Mac

  Python基础——输出[print()]与输入[input()]

  Python基础——数据类型与基本运算【主要为除法】

       Python基础——字符串

       Python基础——条件判断

       Python基础——for/while循环

  上述六篇均为Python 3.x的基础知识。九尺高台,起于累土。学习Python就要从最基本开始,经过逐步的积累,才能有所成就。

  Python基础知识再次回顾好了,接下来该干嘛呢?这不继续Python数据结构了吗?

  上次我写了有关Python数据结构(列表、元组、字典)的3篇随笔:

  Python数据结构之一——list(列表)

  Python数据结构之二——tuple(元组)

  Python数据结构之三——dict(字典)

  本篇随笔将开始一段关于set(集合)之旅吧。

  什么是集合呢?

  说到集合,我首先想到了高中的数学。高中,人生学习中最繁忙的一段时光。直到现在,我能回忆起最多的就是学习、学习、还是读书……言归正传,高一时的数学,我们就接触到了集合。书中应该是这样定义的:

  集合:由一个或多个确定的元素所构成的整体。若x是集合A的元素,则记作xA

  集合中的元素有三个特征:

  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()。

复制代码
1 #创建空集合
2 >>>a = set()
3 >>>a
4 set()
5 >>>type(a)
6 <class 'set'>
复制代码

  注:不能使用{},{}用于创建空字典。

1.2 创建非空集合

  非空集合可以用大括号{}或 set() 函数来创建。

复制代码
 1 #创建集合
 2 >>>a={'a','b','c','d'}
 3 >>>b=set('abcdefabcd')
 4 >>>c=set({'a':1,'b':2,'c':3})
 5 >>>d=set(['a','b','c','a'])
 6 #运行结果
 7 >>>print(a,type(a))
 8 {'c', 'd', 'b', 'a'} <class 'set'>
 9 >>>print(b,type(b))
10 {'f', 'e', 'b', 'c', 'd', 'a'} <class 'set'>
11 >>>print(c,type(c))
12 {'b', 'a','c'} <class 'set'>
13 >>>print(d,type(d))
14 {'c', 'b', 'a'} <class 'set'>
复制代码

  特别地,set中的元素是无序的,并且重复元素在set中自动被过滤。

1 #set中重复元素被自动过滤
2 >>>s = {1,2,,1,2,4,4,3,3}
3 >>>s
4 {1,2,3,4}

 

功能属性

  set有很多很多的功能属性。你们不信?不信的话,继续往下看呗~~~

  set功能属性如下:

复制代码
1 class set(object):2     """3     set() -> new empty set object4     set(iterable) -> new set object5     6     Build an unordered collection of unique elements.7     """8     def add(self, *args, **kwargs): # real signature unknown9         """10         Add an element to a set.11         12         This has no effect if the element is already present.13         """14         pass15 16     def clear(self, *args, **kwargs): # real signature unknown17         """ Remove all elements from this set. """18         pass19 20     def copy(self, *args, **kwargs): # real signature unknown21         """ Return a shallow copy of a set. """22         pass23 24     def difference(self, *args, **kwargs): # real signature unknown25         """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         pass31 32     def difference_update(self, *args, **kwargs): # real signature unknown33         """ Remove all elements of another set from this set. """34         pass35 36     def discard(self, *args, **kwargs): # real signature unknown37         """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         pass43 44     def intersection(self, *args, **kwargs): # real signature unknown45         """46         Return the intersection of two sets as a new set.47         48         (i.e. all elements that are in both sets.)49         """50         pass51 52     def intersection_update(self, *args, **kwargs): # real signature unknown53         """ Update a set with the intersection of itself and another. """54         pass55 56     def isdisjoint(self, *args, **kwargs): # real signature unknown57         """ Return True if two sets have a null intersection. """58         pass59 60     def issubset(self, *args, **kwargs): # real signature unknown61         """ Report whether another set contains this set. """62         pass63 64     def issuperset(self, *args, **kwargs): # real signature unknown65         """ Report whether this set contains another set. """66         pass67 68     def pop(self, *args, **kwargs): # real signature unknown69         """70         Remove and return an arbitrary set element.71         Raises KeyError if the set is empty.72         """73         pass74 75     def remove(self, *args, **kwargs): # real signature unknown76         """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         pass82 83     def symmetric_difference(self, *args, **kwargs): # real signature unknown84         """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         pass90 91     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown92         """ Update a set with the symmetric difference of itself and another. """93         pass94 95     def union(self, *args, **kwargs): # real signature unknown96         """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()方法,并且不生成一个新的集合。

复制代码
 1 #添加元素:add()
 2 >>>s = {1,2,3}
 3 >>>s.add(4)
 4 >>>s
 5 {1,2,3,4}
 6 >>>s.add('g')
 7 >>>s
 8 {1,2,3,4,'g'}
 9 >>>s.add(4)
10 >>>s
11 {1,2,3,4,'g'}
复制代码

  add()方法可以向set中添加元素,可以重复添加,但不会有效果。

  2. 删除元素

   set中利用remove()方法可以删除集合中的元素。

复制代码
1 #删除元素
2 >>>s
3 {1,2,3,4,'g'}
4 >>>s.remove('g')
5 >>>s
6 {1,2,3,4}
复制代码

  3. 清空元素

  clear()方法可以清空set中的元素。

复制代码
1 #清空元素
2 >>>a = {1,2,3,4}
3 >>>b = a.clear()
4 >>>print(a,type(a))
5 set() <class 'set'>
6 >>>print(b,type(b))
7 None <class 'NoneType'>
复制代码

  4. 复制元素

  copy()方法只能浅拷贝set中的元素,并生成一个新的集合。

复制代码
 1 #浅拷贝:copy()
 2 >>>a = {1,(9,2),3}
 3 >>>b = a.copy()
 4 >>>print(a,id(a))
 5 {(9, 2), 1, 3} 2097937619880
 6 >>>print(b,id(b))
 7 {(9, 2), 1, 3} 2097937620776
 8 
 9 #赋值
10 >>>s = {1,2,3,4}
11 >>>d = s
12 >>>print(s,id(s))
13 {1, 2, 3, 4} 2097937785128
14 >>>print(d,id(d))
15 {1, 2, 3, 4} 2097937785128
复制代码

  5. pop()

  pop()方法用于从set中随机取一个元素。记住,是随机的~~~

复制代码
1 #pop()方法
2 >>>s = {1,2,3,4,5,'g','s'}
3 >>>s.pop()
4 'g'
5 >>>s.pop()
6 3
复制代码

  6. set集合操作

  set与数学中的集合类似,是无序的和无重复元素的集合。因此,在Python中,set可以进行交集、并集、补集等操作。

Python set集合操作
数学符号Python符号含义
- 或\-差集,相对补集
&交集
|并集
!=不等于
==等于
in是成员关系
not in非成员关系

 

复制代码
 1 #set集合操作
 2 >>>s = {1,2,3,4}
 3 >>>d = {2.3.5.6}
 4 >>>s & d
 5 {2.3}
 6 >>>s | d
 7 {1,2,3,4,5,6}
 8 >>>s - d
 9 {1,4}
10 >>>d - s
11 {5,6}
复制代码

  set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。因此,最常用的key是字符串。

“思想者”

  set中存储着key,集合中不能放入可变的对象。之前的文章也说过:tuple是不可变的,而list是可变的。因此,set中是可以存储tuple的。这是真的吗?

  时间是检验真理的唯一标准。下面请看示例代码:

复制代码
 1 #tuple可以作为集合中的元素
 2 >>>s = {(1,),(1,2,3),1,2,'g'}
 3 >>>s
 4 {(1,),(1,2,3),1,2,'g'}
 5 
 6 #tuple也有失灵的时候
 7 >>>t = (1,2,[1,2,3],4)
 8 >>>type(t)
 9 <class 'tuple'>
10 >>>d = {1,2,(1,2,[1,2,3],4)}
11 Traceback (most recent call last):
12   File "<stdin>", line 1, in <module>
13 TypeError: unhashable type: 'list'
复制代码

  为什么会有错误呢?我也不清楚哎~~~这里面的道道很深,请读者细细体会。

  set是一种数据结构。如果要详细的介绍set,我应该可以去出书了。这篇随笔只是起到入门的效果。

  正所谓“师傅”领进门,修行靠大家嘛!

 

出处:http://www.cnblogs.com/SmallWZQ/p/8488744.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391043.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

knn 机器学习_机器学习:通过预测意大利葡萄酒的品种来观察KNN的工作方式

knn 机器学习Introduction介绍 For this article, I’d like to introduce you to KNN with a practical example.对于本文&#xff0c;我想通过一个实际的例子向您介绍KNN。 I will consider one of my project that you can find in my GitHub profile. For this project, …

python 实现分步累加_Python网页爬取分步指南

python 实现分步累加As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry.作为数据科学家&#xff0c;我们一直在寻找…

关于双黑洞和引力波,LIGO科学家回答了这7个你可能会关心的问题

引力波的成功探测&#xff0c;就像双黑洞的碰撞一样&#xff0c;一石激起千层浪。 关于双黑洞和引力波&#xff0c;LIGO科学家回答了这7个你可能会关心的问题 最近&#xff0c;引力波的成功探测&#xff0c;就像双黑洞的碰撞一样&#xff0c;一石激起千层浪。 大家兴奋之余&am…

用于MLOps的MLflow简介第1部分:Anaconda环境

在这三部分的博客中跟随了演示之后&#xff0c;您将能够&#xff1a; (After following along with the demos in this three part blog you will be able to:) Understand how you and your Data Science teams can improve your MLOps practices using MLflow 了解您和您的数…

pymc3 贝叶斯线性回归_使用PyMC3估计的贝叶斯推理能力

pymc3 贝叶斯线性回归内部AI (Inside AI) If you’ve steered clear of Bayesian regression because of its complexity, this article shows how to apply simple MCMC Bayesian Inference to linear data with outliers in Python, using linear regression and Gaussian ra…

mongodb分布式集群搭建手记

一、架构简介 目标 单机搭建mongodb分布式集群(副本集 分片集群)&#xff0c;演示mongodb分布式集群的安装部署、简单操作。 说明 在同一个vm启动由两个分片组成的分布式集群&#xff0c;每个分片都是一个PSS(Primary-Secondary-Secondary)模式的数据副本集&#xff1b; Confi…

python16_day37【爬虫2】

一、异步非阻塞 1.自定义异步非阻塞 1 import socket2 import select3 4 class Request(object):5 def __init__(self,sock,func,url):6 self.sock sock7 self.func func8 self.url url9 10 def fileno(self): 11 return self.soc…

朴素贝叶斯实现分类_关于朴素贝叶斯分类及其实现的简短教程

朴素贝叶斯实现分类Naive Bayes classification is one of the most simple and popular algorithms in data mining or machine learning (Listed in the top 10 popular algorithms by CRC Press Reference [1]). The basic idea of the Naive Bayes classification is very …

2019年度年中回顾总结_我的2019年回顾和我的2020年目标(包括数量和收入)

2019年度年中回顾总结In this post were going to take a look at how 2019 was for me (mostly professionally) and were also going to set some goals for 2020! &#x1f929; 在这篇文章中&#xff0c;我们将了解2019年对我来说(主要是职业)如何&#xff0c;我们还将为20…

vray阴天室内_阴天有话:第1部分

vray阴天室内When working with text data and NLP projects, word-frequency is often a useful feature to identify and look into. However, creating good visuals is often difficult because you don’t have a lot of options outside of bar charts. Lets face it; ba…

高光谱图像分类_高光谱图像分析-分类

高光谱图像分类初学者指南 (Beginner’s Guide) This article provides detailed implementation of different classification algorithms on Hyperspectral Images(HSI).本文提供了在高光谱图像(HSI)上不同分类算法的详细实现。 目录 (Table of Contents) Introduction to H…

机器人的动力学和动力学联系_通过机器学习了解幸福动力学(第2部分)

机器人的动力学和动力学联系Happiness is something we all aspire to, yet its key factors are still unclear.幸福是我们所有人都渴望的东西&#xff0c;但其关键因素仍不清楚。 Some would argue that wealth is the most important condition as it determines one’s li…

ubuntu 16.04 安装mysql

2019独角兽企业重金招聘Python工程师标准>>> 1) 安装 sudo apt-get install mysql-server apt-get isntall mysql-client apt-get install libmysqlclient-dev 2) 验证 sudo netstat -tap | grep mysql 如果有 就代表已经安装成功。 3&#xff09;开启远程访问 1、 …

大样品随机双盲测试_训练和测试样品生成

大样品随机双盲测试This post aims to explore a step-by-step approach to create a K-Nearest Neighbors Algorithm without the help of any third-party library. In practice, this Algorithm should be useful enough for us to classify our data whenever we have alre…

JavaScript 基础,登录验证

<script></script>的三种用法&#xff1a;放在<body>中放在<head>中放在外部JS文件中三种输出数据的方式&#xff1a;使用 document.write() 方法将内容写到 HTML 文档中。使用 window.alert() 弹出警告框。使用 innerHTML 写入到 HTML 元素。使用 &qu…

从数据角度探索在新加坡的非法毒品

All things are poisons, for there is nothing without poisonous qualities. It is only the dose which makes a thing poison.” ― Paracelsus万物都是毒药&#xff0c;因为没有毒药就没有什么。 只是使事物中毒的剂量。” ― 寄生虫 执行摘要(又名TL&#xff1b; DR) (Ex…

Android 自定义View实现QQ运动积分抽奖转盘

因为偶尔关注QQ运动&#xff0c; 看到QQ运动的积分抽奖界面比较有意思&#xff0c;所以就尝试用自定义View实现了下&#xff0c;原本想通过开发者选项查看下界面的一些信息&#xff0c;后来发现积分抽奖界面是在WebView中展示的&#xff0c;应该是在H5页面中用js代码实现的&…

瑞立视:厚积薄发且具有“工匠精神”的中国品牌

一家成立两年的公司&#xff1a;是如何在VR行业趋于稳定的情况下首次融资就获得如此大额的金额呢&#xff1f; 2017年VR行业内宣布融资的公司寥寥无几&#xff0c;无论是投资人还是消费者对这个 “宠儿”都开始纷纷投以怀疑的目光。但就在2017年7月27日&#xff0c;深圳市一家…

CSV模块的使用

CSV模块的使用 1、csv简介 CSV (Comma Separated Values)&#xff0c;即逗号分隔值&#xff08;也称字符分隔值&#xff0c;因为分隔符可以不是逗号&#xff09;&#xff0c;是一种常用的文本 格式&#xff0c;用以存储表格数据&#xff0c;包括数字或者字符。很多程序在处理数…

python 重启内核_Python从零开始的内核回归

python 重启内核Every beginner in Machine Learning starts by studying what regression means and how the linear regression algorithm works. In fact, the ease of understanding, explainability and the vast effective real-world use cases of linear regression is…