Python 集合 intersection() 方法
定义和用法
intersection() 方法返回包含两个或更多集合之间相似性的集合。
含义:返回的集合仅包含两个集合中都存在的项目,或者如果使用两个以上的集合进行比较,则在所有集合中都存在。
实例
例子 1
返回包含存在于集合 x 和集合 y 中的项目的集合:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
例子 2
对比 3 个集合,并返回存在于所有 3 个集合中的项目:
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)
语法
set.intersection(set1, set2 ... etc)
参数
| 参数 | 描述 |
|---|---|
| set1 | 必需。要在其中检索相同项目的集合。 |
| set2 |
可选。其他需要在其中检索相同项目的集合。 您可以比较任意多的集合。 集合之间由逗号分隔。 |