Python 數據結構詳解——集合

Python 數據結構詳解——集合

set對象官方文檔:

在Python中,set對象是一組無序且hash值唯一的對象.常用於測試是否包含,去重,以及進行諸如交集,合集,差集,對稱差集等數學運算.

正如其它的collection模塊一樣,set支持x in set, len(set)以及for x in set操作.作爲一個無序的集合,set不會記錄元素的位置或者插入順序.由此,set不支持索引,切片或者其它序列行爲.

目前有兩種內置的set類型,set和frozenset.set是可變的——可以使用add()和move()方法改變內容.由於是可變的,set對象沒有hash值,不能作爲字典的關鍵字或者另一個set的元素.frozenset是不可變以及可hash的——它的內容在創建後不能改變;它就可以作爲字典的key或者另一個set的元素.
set和frozenset使用方式大多是一樣的.他們支持以下操作:

len(s)  # 返回元素的個數
x in s  # 判斷x是否在s中
isdisjoint(other)  # 如果和其它的集合交集爲空,則返回True

# 是否爲子集的判斷
set <= other
set < other
set >= other
set > other

set | other | ...  # 返回並集
set & other & ...  # 返回交集
set - other - ...  # 返回在set中,但不在其它集合中的元素
set ^ other  # 返回僅在set或者other中的元素

可以通過如下方式更新set:

set |= other | other | ...  # 將其它集合的元素添加到set中
set &= other & ...  # 將交集更新set
set -= other | ...  # 更新set,去除set中包含在other中的元素
set ^= other  # 更新set,保存僅在set或者other中的元素
add()  # 添加元素
remove()  # 刪除元素, 沒有該元素則報錯
discard()  # 如果元素在集合中,則刪除元素
pop()  # 任意刪除一個元素,集合爲空則報錯
clear()  # 刪除所有元素

使用示例

去重,成員判斷,迭代

a = [1,2,3,1,5,2]
a_s = set(a)

print(f'a: {a}')
print(f'a_s: {a_s}')
print(f'len(a_s): {len(a_s)}')
print(f'1 in a_s: {1 in a_s}')
print(f'1 in a_s: {4 in a_s}')
a: [1, 2, 3, 1, 5, 2]
a_s: {1, 2, 3, 5}
len(a_s): 4
1 in a_s: True
1 in a_s: False
for s in a_s:
    print(s, end=', ')
1, 2, 3, 5, 

集合運算

sa = {1,2,3,4,5}
sb = {3,4,5,6,7}
sc = {8,9,0}

是否重疊(交集是否爲空)

print(f'sa和sb交集是否爲空:{sa.isdisjoint(sb)}')
print(f'sa和sc交集是否爲空:{sa.isdisjoint(sc)}')
sa和sb交集是否爲空:False
sa和sc交集是否爲空:True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章