1. 程式人生 > >Python基礎操作-集合

Python基礎操作-集合

col ror pycha union .py -s rac trac 子集

Python set是基本數據類型的一種集合類型,它有可變集合(set())和不可變集合(frozenset)兩種。創建集合set集合set添加集合刪除交集並集差集的操作都是非常實用的方法。

list_1 = set([1,3,5,7,5,8,10])

list_2 = set([2,3,4,5,6,7,8])

list_3 = set([1,3,5])

一:基本操作

添加一個add

list_1.add(123)
print(list_1)
{1, 3, 5, 7, 8, 10, 123}

添加多個update

list_1.update([10,20,30,50])
print(list_1)
{1, 3, 5, 7, 8, 10, 50, 20 , 30}

刪除remove 如果刪除列表內沒有的則會報錯

list_1.remove(1)
print(list_1)
{3, 5, 7, 8, 10}

list_1.remove(20)
print(list_1)


Traceback (most recent call last):
File "D:/PyCharm/day1/集合測試.py", line 14, in <module>
list_1.remove(20)
KeyError: 20

刪除discard 如果刪除列表內沒有的不會報錯

list_1.discard(20)
print(list_1)
{1, 3, 5, 7, 8, 10}

刪除pop 隨機刪除一個成員

list_1.pop()
print(list_1)
{3, 5, 7, 8, 10}

二:關系測試

交集

print(list_1.intersection(list_2))

{8, 3, 5, 7}

並集

print(list_1.union(list_2))

{1, 2, 3, 4, 5, 6, 7, 8, 10}

差集

print(list_1.difference(list_2))

{1, 10}

子集

print(list_3.issubset(list_1))

True

父集

print(list_1.issuperset(list_3))

True

對稱差集

print(list_1.symmetric_difference(list_2))

{1, 2, 4, 6, 10}

Python基礎操作-集合