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.pswp.cn/news/391043.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391043.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391043.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

volatile關鍵字有什么用

問題&#xff1a;volatile關鍵字有什么用 在工作的時候&#xff0c;我碰到了volatile關鍵字。但是我不是非常了解它。我發現了這個解釋 這篇文章已經解釋了問題中的關鍵字的細節了&#xff0c;你們曾經用過它嗎或者見過正確使用這個關鍵字的樣例 回答 Java中同步的實現大多是…

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, …

MMU內存管理單元(看書筆記)

http://note.youdao.com/noteshare?id8e12abd45bba955f73874450e5d62b5b&subD09C7B51049D4F88959668B60B1263B5 筆記放在了有道云上面了&#xff0c;不想再寫一遍了。 韋東山《嵌入式linux完全開發手冊》看書筆記轉載于:https://www.cnblogs.com/coversky/p/7709381.html

Java中如何讀取文件夾下的所有文件

問題&#xff1a;Java中如何讀取文件夾下的所有文件 Java里面是如何讀取一個文件夾下的所有文件的&#xff1f; 回答一 public void listFilesForFolder(final File folder) {for (final File fileEntry : folder.listFiles()) {if (fileEntry.isDirectory()) {listFilesFor…

github pages_如何使用GitHub Actions和Pages發布GitHub事件數據

github pagesTeams who work on GitHub rely on event data to collaborate. The data recorded as issues, pull requests, and comments become vital to understanding the project.在GitHub上工作的團隊依靠事件數據進行協作。 記錄為問題&#xff0c;請求和注釋的數據對于…

c# .Net 緩存 使用System.Runtime.Caching 做緩存 平滑過期,絕對過期

1 public class CacheHeloer2 {3 4 /// <summary>5 /// 默認緩存6 /// </summary>7 private static CacheHeloer Default { get { return new CacheHeloer(); } }8 9 /// <summary>10 /// 緩存初始化11 /// </summary>12 …

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;我們一直在尋找…

Java 到底有沒有析構函數呢?

Java 到底有沒有析構函數呢&#xff1f; ? ? Java 到底有沒有析構函數呢&#xff1f;我沒能找到任何有關找個的文檔。如果沒有的話&#xff0c;我要怎么樣才能達到一樣的效果&#xff1f; ? ? ? 為了使得我的問題更加具體&#xff0c;我寫了一個應用程序去處理數據并且說…

關于雙黑洞和引力波,LIGO科學家回答了這7個你可能會關心的問題

引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 關于雙黑洞和引力波&#xff0c;LIGO科學家回答了這7個你可能會關心的問題 最近&#xff0c;引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 大家興奮之余&am…

如何使用HTML,CSS和JavaScript構建技巧計算器

A Tip Calculator is a calculator that calculates a tip based on the percentage of the total bill.小費計算器是根據總賬單的百分比計算小費的計算器。 Lets build one now.讓我們現在建立一個。 第1步-HTML&#xff1a; (Step 1 - HTML:) We create a form in order to…

用于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 了解您和您的數…

[WCF] - 使用 [DataMember] 標記的數據契約需要聲明 Set 方法

WCF 數據結構中返回的只讀屬性 TotalCount 也需要聲明 Set 方法。 [DataContract]public class BookShelfDataModel{ public BookShelfDataModel() { BookList new List<BookDataModel>(); } [DataMember] public List<BookDataModel>…

sql注入語句示例大全_SQL Group By語句用示例語法解釋

sql注入語句示例大全GROUP BY gives us a way to combine rows and aggregate data.GROUP BY為我們提供了一種合并行和匯總數據的方法。 The data used is from the campaign contributions data we’ve been using in some of these guides.使用的數據來自我們在其中一些指南…

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么?

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么&#xff1f; 我有一個會被多個線程同時修改的Map 在Java的API里面&#xff0c;有3種不同的實現了同步的Map實現 HashtableCollections.synchronizedMap(Map)ConcurrentHashMap 據我所知&#xff0c;HashT…

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…

Hadoop Streaming詳解

一&#xff1a; Hadoop Streaming詳解 1、Streaming的作用 Hadoop Streaming框架&#xff0c;最大的好處是&#xff0c;讓任何語言編寫的map, reduce程序能夠在hadoop集群上運行&#xff1b;map/reduce程序只要遵循從標準輸入stdin讀&#xff0c;寫出到標準輸出stdout即可 其次…

mongodb分布式集群搭建手記

一、架構簡介 目標 單機搭建mongodb分布式集群(副本集 分片集群)&#xff0c;演示mongodb分布式集群的安裝部署、簡單操作。 說明 在同一個vm啟動由兩個分片組成的分布式集群&#xff0c;每個分片都是一個PSS(Primary-Secondary-Secondary)模式的數據副本集&#xff1b; Confi…

歸約歸約沖突_JavaScript映射,歸約和過濾-帶有代碼示例的JS數組函數

歸約歸約沖突Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why …

為什么Java里面的靜態方法不能是抽象的

為什么Java里面的靜態方法不能是抽象的&#xff1f; 問題是為什么Java里面不能定義一個抽象的靜態方法&#xff1f;例如&#xff1a; abstract class foo {abstract void bar( ); // <-- this is okabstract static void bar2(); //<-- this isnt why? }回答一 因為抽…

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…