Python 中的 intersection() 函数有助于查找集合中的公共元素。此函数返回一个新集合,其中包含所有比较集合中的公共元素。
A.intersection(*other_sets) #where A is a set of any iterables, like strings, lists, and dictionaries.
intersection() 函数可以接受多个集合参数进行比较(* 表示),并用逗号分隔集合。我们也可以使用 & 运算符(交集运算符)来查找集合的交集。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| A | 要搜索相等项的集合 | 必需 |
| 其他集合 | 要搜索相等项的另一个集合。 | 可选 |
返回值始终是一个集合。如果没有传递参数,它将返回集合的浅拷贝。
| 输入 | 返回值 |
|---|---|
| 集合 | 包含公共元素的集合 |
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'}
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'}
{}