溫馨提示×

set類型在Python中的交集、并集、差集如何計算

小樊
154
2024-09-06 13:06:29
欄目: 編程語言

在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}

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女