在 Python 中計算集合交集

在 Python 中使用 `intersection()` 函式設定交集

``````set1 = {1, 2, 3, 4}
set2 = {2, 4, 6, 8}
set3 = set1.intersection(set2)
print(set3)
``````

``````{2, 4}
``````

``````set1 = {1, 2, 3, 4}
set2 = {2, 4, 6, 8}
set3 = {2, 3, 5, 7}
set4 = set1.intersection(set2, set3)
print(set4)
``````

``````{2}
``````

在 Python 中使用 `&` 運算子來計算集合交集

`&` 運算子 也可用於在 Python 中執行集合交集。`&` 運算子返回其兩個運算元中的公共值。`&` 運算子的返回型別是一個集合。請參考以下程式碼片段。

``````set1 = {1, 2, 3, 4}
set2 = {2, 4, 6, 8}
set3 = set1 & set2
print(set3)
``````

``````{2, 4}
``````

``````set1 = {1, 2, 3, 4}
set2 = {2, 4, 6, 8}
set3 = {2, 3, 5, 7}
set4 = set1 & set2 & set3
print(set4)
``````

``````{2}
``````

在 Python 中使用 `intersection_update()` 函式來計算集合交集

``````set1 = {1, 2, 3, 4}
set2 = {2, 4, 6, 8}
set1.intersection_update(set2)
print(set1)
``````

``````{2, 4}
``````

``````set1 = {1, 2, 3, 4}
set2 = {2, 4, 6, 8}
set3 = {2, 3, 5, 7}
set1.intersection_update(set2, set3)
print(set1)
``````

``````{2}
``````

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.