微信公衆號:「Python讀財」
如有問題或建議,請公衆號留言
Python中的集合和數學上的集合是一個概念,基本功能包括關係測試和消除重複元素,對於集合還可以進行數學上的交、並、差運算。定義一個集合的方式,見下面的代碼:
①使用set()
函數
In [18]: color_set = set(['green','blue','red','yellow','blue'])
In [20]: color_set
Out[20]: {'blue', 'green', 'red', 'yellow'}
②使用{}
定義,需要注意的是{}
必須含有元素,空的{}
定義的是空的字典
In [19]: color_set = {'green','blue','red','yellow','blue'}
In [20]: color_set
Out[20]: {'blue', 'green', 'red', 'yellow'}
可以看到,set()
會幫你去掉重複的元素(上方的'blue'
),下面講一下集合的常見操作
判斷一個元素是否在集合內
寫法:element in set
In [21]: 'blue' in color_set
Out[21]: True
In [22]: 'white' in color_set
Out[22]: False
往集合中添加元素
寫法:set.add(element)
In [23]: color_set.add('white')
In [24]: color_set
Out[24]: {'blue', 'green', 'red', 'white', 'yellow'}
# 若添加集合中已有的元素
# 則會自動去重
In [25]: color_set.add('blue')
In [26]: color_set
Out[26]: {'blue', 'green', 'red', 'white', 'yellow'}
移除元素
寫法:set.remove(element)
In [27]: color_set.remove('white')
In [28]: color_set
Out[28]: {'blue', 'green', 'red', 'yellow'}
取集合的並集
寫法:set_1.union(set_2)
In [29]: color_set1 = set(['green','blue','red','yellow','blue'])
In [30]: color_set2 = set(['purple','blue','pink','black'])
In [31]: color_set1.union(color_set2)
Out[31]: {'black', 'blue', 'green', 'pink', 'red', 'purple', 'yellow'}
取集合的交集
寫法:set_1.intersection(set_2)
In [29]: color_set1 = set(['green','blue','red','yellow','blue'])
In [30]: color_set2 = set(['purple','blue','pink','black'])
In [32]: color_set1.intersection(color_set2)
Out[32]: {'blue'}
取集合的差集
寫法:set_1.difference(set_2)
In [29]: color_set1 = set(['green','blue','red','yellow','blue'])
In [30]: color_set2 = set(['purple','blue','pink','black'])
# ①在color_set1中去掉color_set2含有的元素
In [33]: color_set1.difference(color_set2)
Out[33]: {'green', 'red', 'yellow'}
# ②在color_set2中去掉color_set1含有的元素
In [34]: color_set2.difference(color_set1)
Out[34]: {'black', 'pink', 'purple'}
練習題:
- 給定兩個列表,分別爲
[1, 2, 3, 3, 4, 4, 5]
和[1, 1, 3, 5, 5, 7, 9]
,請根據這兩個列表分別生成集合A和B - 往集合A中加入元素
5和7
,往集合B中加入元素6和9
- 求集合A和集合B的並集
- 求集合A和集合B的交集
- 求A-B和B-A
掃碼關注公衆號「Python讀財」,第一時間獲取乾貨,還可以加Python學習交流羣!!