Python中的set(集合)是一個無序且不包含重復元素的數據類型。它支持以下操作:
創建集合:可以使用花括號{}
創建一個集合,或者在聲明時直接使用set()
函數。例如:
my_set = {1, 2, 3}
my_set2 = set([1, 2, 3])
添加元素:使用add()
方法向集合中添加一個元素。例如:
my_set.add(4)
刪除元素:使用remove()
或discard()
方法從集合中刪除一個元素。remove()
方法在元素不存在時會拋出異常,而discard()
方法則不會。例如:
my_set.remove(4)
my_set.discard(5)
集合長度:使用內置函數len()
獲取集合中元素的個數。例如:
length = len(my_set)
成員關系測試:使用in
或not in
關鍵字檢查一個元素是否在集合中。例如:
if 3 in my_set:
print("3 is in the set")
遍歷集合:使用for循環遍歷集合中的元素。例如:
for item in my_set:
print(item)
集合運算:
union()
方法或|
運算符計算兩個集合的并集。例如:result = my_set.union(another_set)
result = my_set | another_set
intersection()
方法或&
運算符計算兩個集合的交集。例如:result = my_set.intersection(another_set)
result = my_set & another_set
difference()
方法或-
運算符計算兩個集合的差集。例如:result = my_set.difference(another_set)
result = my_set - another_set
symmetric_difference()
方法或^
運算符計算兩個集合的對稱差集。例如:result = my_set.symmetric_difference(another_set)
result = my_set ^ another_set
issubset()
、issuperset()
方法或<=
、>=
運算符檢查一個集合是否是另一個集合的子集或超集。例如:if my_set.issubset(another_set):
print("my_set is a subset of another_set")
if my_set.issuperset(another_set):
print("my_set is a superset of another_set")