Python intersection()
更新:2022-07-24 13:04
python
中的 intersection()
函数有助于找到集合中的公共元素。该函数返回一个包含所有比较集中共有元素的新集合。
A.intersection(*other_sets) # where A is a set of any iterables, like strings, lists, and dictionaries.
交集()参数:
intersection()
函数可以接受许多用于比较的集合参数(*
表示),并用逗号分隔这些集合。我们还可以使用 &
运算符(交集运算符)来查找集合的交集。
参数 | 描述 | 必需/可选 |
---|---|---|
A | 要在其中搜索相等项目的集合 | 需要 |
其他集 | 另一组用于搜索相等的项目 | 可选 |
交集()返回值
返回值总是一个集合。如果没有传递任何参数,它将返回该集合的一个浅层副本。
输入 | 返回值 |
---|---|
集合 | 有共同元素的集合 |
Python intersection()
方法示例
示例 1: intersection()
在 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'}
{}