在Python中,可以使用內置的set類型來計算兩個集合的交集、并集和差集。這里是一些例子:
# 定義兩個集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 計算交集
intersection = set1.intersection(set2)
print("Intersection:", intersection) # 輸出:{4, 5}
# 計算并集
union = set1.union(set2)
print("Union:", union) # 輸出:{1, 2, 3, 4, 5, 6, 7, 8}
# 計算差集
difference = set1.difference(set2)
print("Difference:", difference) # 輸出:{1, 2, 3}
你還可以使用其他方法,比如 & 運算符計算交集,| 運算符計算并集,- 運算符計算差集:
# 計算交集
intersection = set1 & set2
print("Intersection:", intersection) # 輸出:{4, 5}
# 計算并集
union = set1 | set2
print("Union:", union) # 輸出:{1, 2, 3, 4, 5, 6, 7, 8}
# 計算差集
difference = set1 - set2
print("Difference:", difference) # 輸出:{1, 2, 3}