python之集合

集合的定義

PS.集合不能爲空

##集合可以是普通的數字
In [1]: s1 = {1,2,3}

In [2]: type(s1)
Out[2]: set

##集合是一個無序的,不重複的數據組合
In [3]: s2 = {1,2,3,2,3,4}

In [4]: s2
Out[4]: {1, 2, 3, 4}

In [5]: type(s2)
Out[5]: set

##集合可以含有字符串
In [6]: s3 = {1,2,3,'hello'}

In [7]: type(s3)
Out[7]: set

##集合可以含有元組
In [8]: s4 = {1,2,3,'hello',(1,2,3)}

In [9]: type(s4)
Out[9]: set

##因爲集合是無序的,所以集合不能含有列表
In [10]: s5 = {1,2,3,'hello',(1,2,3),[1,2,3]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-b181079b4888> in <module>()
----> 1 s5 = {1,2,3,'hello',(1,2,3),[1,2,3]}

TypeError: unhashable type: 'list'

集合的應用

集合是一個無序的,不重複的數據組合

1)列表去重
In [12]: set = {1,2,3,1,1,2,3,'hello'}

In [13]: set
Out[13]: {1, 2, 3, 'hello'}

2)關係的測試

集合的關係

python中:

s1 = {1, 2, 3, 100}
s2 = {1, 2, 'hello'}

交集:
print s1.intersection(s2)
並集:
print s1.union(s2)
差集:
print s1.difference(s2)
print s2.difference(s1)
對等差分:
print s1.symmetric_difference(s2)

##子集 list_1.issubset(list_2)
##父集 list_1.issuperset(list_2)
##有無交集 list_1.isdisjoint(list_2)

這裏寫圖片描述

數學中:

s1 = {1,2,100}
s2 = {1,2,3,'hello'}

交集:
print s1 & s2
並集:
print s1 | s2
差集:
print s1 - s2
print s2 - s1
對等差分:
print s1 ^ s2

這裏寫圖片描述

集合的添加

In [1]: s = {1,2,3,'hello'}

##s.add()在集合中添加一項
In [2]: s.add(23)

In [3]: s
Out[3]: {1, 2, 3, 23, 'hello'}

##s.update()在集合中添加多項,可迭代
In [4]: s.update(['world','1'])

In [5]: s
Out[5]: {1, 2, 3, 23, '1', 'hello', 'world'}

集合的刪除

In [6]: s
Out[6]: {1, 2, 3, 23, '1', 'hello', 'world'}

##s.remove()刪除集合中指定的元素
In [7]: s.remove('1')

In [8]: s
Out[8]: {1, 2, 3, 23, 'hello', 'world'}

##s.pop()隨機刪除集合中的元素,並返回刪除的元素
In [9]: s.pop()
Out[9]: 1

In [10]: s
Out[10]: {2, 3, 23, 'hello', 'world'}

集合的其他操作

##len(s)顯示集合的長度
In [11]: len(s)
Out[11]: 5

In [12]: s
Out[12]: {2, 3, 23, 'hello', 'world'}

##判斷元素是否屬於集合
In [13]: 2 in s
Out[13]: True

In [14]: 1 in s
Out[14]: False

集合的其他操作

##s.copy()集合的淺拷貝
##s.clear()清空集合的所有元素
In [15]: s
Out[15]: {2, 3, 23, 'hello', 'world'}

In [16]: s.clear()

In [17]: s
Out[17]: set()
發佈了87 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章