Python小白零基礎入門 —— 集合(set)

微信公衆號:「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'}

並集.png

取集合的交集

寫法: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'}

交集.png

取集合的差集

寫法: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.png

差集2.png

練習題:

  1. 給定兩個列表,分別爲[1, 2, 3, 3, 4, 4, 5][1, 1, 3, 5, 5, 7, 9],請根據這兩個列表分別生成集合A和B
  2. 往集合A中加入元素5和7,往集合B中加入元素6和9
  3. 求集合A和集合B的並集
  4. 求集合A和集合B的交集
  5. 求A-B和B-A

掃碼關注公衆號「Python讀財」,第一時間獲取乾貨,還可以加Python學習交流羣!!
底部二維碼.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章