Python之set集合詳解


定義

set(集合)是Python中常見的一種數據類型。集合中的元素是無序唯一的,它主要用於進行關系測試消除重復元素。集合對象還支持union(聯合),intersection(交集),difference(差集),sysmmetric difference(對稱差集)等數學運算。

創建集合set

創建空集合

s = set()  # 空集合
print(type(s))  # <class 'set'>
s1 = {}  # 空字典
print(type(s1))  # <class 'dict'>

注意:想要創建空集合,你必須使用set()而不是{},后者用於創建空字典。

創建非空集合

s1 = {1, 2, 3}
print(s1)

s2 = set('HelloWorld')
print(s2)

結果如下

{1, 2, 3}
{'l', 'o', 'W', 'H', 'r', 'd', 'e'}

常用的集合方法

s.add() - 向集合中添加元素

s = {'a', 'b', 'c'}
s.add(666)
print(s)  # {'b', 666, 'c', 'a'}

s.remove() - 刪除集合中的元素

s = {'a', 'b', 'c'}
s.remove('a')
print(s)  # {'b', 'c'}
s.remove('d')  # 刪除集合中不存在的元素會報KeyError錯誤

s.pop() - 刪除並返回任意的集合元素(隨機刪除)

s = {'a', 'b', 'c'}
s.pop()  # 刪除時無序的隨機刪除
print(s)  # {'a', 'b'}

s.discard() - 刪除集合中的元素

s = {'a', 'b', 'c'}
s.discard('a')
s.discard('d')  # 如果元素不存在則不執行任何操作
print(s)  # {'c', 'b'}

s.clear() - 清空集合

s = {'a', 'b', 'c'}
s.clear()
print(s)  # set()

s.copy() - 淺拷貝一個集合

s1 = {'a', 'b', 'c'}  # 可變集合
s2 = frozenset(s1)  # 不可變集合
s1_cp = s1.copy()
s2_cp = s2.copy()
print(s1, s1_cp, id(s1), id(s1_cp))
print(s2, s2_cp, id(s2), id(s2_cp))

結果如下

{'c', 'a', 'b'} {'c', 'a', 'b'} 2553599288040 2553852385768
frozenset({'c', 'a', 'b'}) frozenset({'c', 'a', 'b'}) 2553597533768 2553597533768

在python中,set屬於可變類型,fronzenset則屬於不可變類型。

可變對象的淺拷貝,整體地址不一樣,但是內部元素都是同一個地址(你可以嘗試遍歷集合中的元素來查看元素的地址);

而不可變對象的淺拷貝,整體地址和內部元素都是同一個地址。

s1.issubset(s2) - 子集

子集,為某個集合中一部分的集合,故亦稱部分集合。

使用操作符 < 執行子集操作,同樣地,也可使用方法 issubset() 完成。

s1 = {'a', 'b'}
s2 = {'a', 'b', 'c', 'd'}
s3 = {'a', 'c'}
print(s1.issubset(s2))  # True
print(s1 < s2)  # True
print(s1 < s3)  # False

s1.intersection(s2) - 交集

兩個集合 A 和 B 的交集是含有所有既屬於 A 又屬於 B 的元素,而沒有其他元素的集合。

使用 & 操作符執行交集操作,同樣地,也可使用方法 intersection() 完成。

s1 = {'a', 'b', 'c'}
s2 = {'a', 'b', 'd'}
s3 = s1.intersection(s2)
s4 = s1 & s2  # 效果同上
print(s3)  # {'b', 'a'}
print(s4)  # {'b', 'a'}

s1.union(s2) - 並集

一組集合的並集是這些集合的所有元素構成的集合,而不包含其他元素。

使用操作符 | 執行並集操作,同樣地,也可使用方法 union() 完成。

s1 = {'a', 'b', 'c'}
s2 = {'a', 'b', 'd'}
s3 = s1.union(s2)
s4 = s1 | s2  # 效果同上
print(s3)  # {'a', 'b', 'd', 'c'}
print(s4)  # {'a', 'b', 'd', 'c'}

s1.difference(s2) - 差集

A 與 B 的差集是所有屬於 A 且不屬於 B 的元素構成的集合。

使用操作符 - 執行差集操作,同樣地,也可使用方法 difference() 完成。

s1 = {'a', 'b', 'c'}
s2 = {'a', 'b', 'd'}
s3 = s1.difference(s2)
s4 = s1 - s2  # 效果同上
print(s3)  # {'c'}
print(s4)  # {'c'}

s1.symmetric_difference(s2) - 對稱差

兩個集合的對稱差是只屬於其中一個集合,而不屬於另一個集合的元素組成的集合。

使用 ^ 操作符執行差集操作,同樣地,也可使用方法 symmetric_difference() 完成。

s1 = {'a', 'b', 'c', 'd'}
s2 = {'a', 'b', 'e', 'f'}
s3 = s1.symmetric_difference(s2)
s4 = s1 ^ s2
print(s3)  # {'c', 'e', 'f', 'd'}
print(s4)  # {'c', 'e', 'f', 'd'}

s.update() - 更新集合

s = {'a', 'b', 'c'}
s.update('d')
print(s)  # {'b', 'a', 'c', 'd'}
s.update({'e', 'f'})
print(s)  # {'a', 'f', 'd', 'e', 'b', 'c'}
s.update(['g', 'h'])
print(s)  # {'h', 'a', 'f', 'd', 'e', 'g', 'b', 'c'}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM