是的,在Python中,set
可以進(jìn)行集合運(yùn)算。集合運(yùn)算主要包括并集(union)、交集(intersection)、差集(difference)和對(duì)稱差集(symmetric_difference)。以下是如何使用這些運(yùn)算的示例:
# 定義兩個(gè)集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 并集
union_set = set1.union(set2)
print("并集:", union_set) # 輸出: {1, 2, 3, 4, 5, 6, 7, 8}
# 交集
intersection_set = set1.intersection(set2)
print("交集:", intersection_set) # 輸出: {4, 5}
# 差集
difference_set = set1.difference(set2)
print("差集:", difference_set) # 輸出: {1, 2, 3}
# 對(duì)稱差集
symmetric_difference_set = set1.symmetric_difference(set2)
print("對(duì)稱差集:", symmetric_difference_set) # 輸出: {1, 2, 3, 6, 7, 8}
此外,set
還支持其他操作,如檢查元素是否存在(in
或not in
)、遍歷元素、返回集合大?。?code>len())等。