python 中的交集()函數有助于找到集合中的公共元素。該函數返回一個包含所有比較集中共有元素的新集合。
**A.intersection(*other_sets)** #where A is a set of any iterables, like strings, lists, and dictionaries.
交叉點()參數:
intersection()
函數可以接受許多用于比較的集合參數(*表示),并用逗號分隔這些集合。我們還可以使用&運算符(交集運算符)來查找集合的交集。
參數 | 描述 | 必需/可選 |
---|---|---|
A | 要在其中搜索相等項目的集合 | 需要 |
其他集 | 另一組用于搜索相等的項目。 | 可選擇的 |
交叉點()返回值
返回值總是一個集合。如果沒有傳遞任何參數,它將返回該集合的一個淺層副本。
| 投入 | 返回值 | | 設置 | 有共同元素的集合 |
Python 中的交集()
方法示例
示例 1:交集()在 Python 中是如何工作的?
A = {'a', 'b', 'c', 'd'}
B = {'c', 'e', 'f', 'a'}
C = {'d', 'f', 'a', 'g'}
print(A.intersection(B))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))
輸出:
{'a', 'c'}
{'f', 'a'}
{'a', 'd'}
{'a'}
示例 2:如何使用&運算符設置交集?
A = {'a', 'b', 'c', 'd'}
B = {'c', 'e', 'f', 'a'}
C = {'d', 'f', 'h', 'g'}
print(A & B)
print(B & C)
print(A & C)
print(A & B & C)
輸出:
{'a', 'c'}
{'f'}
{'d'}
{}