Python Set intersection() 方法
示例
返回一个集合,其中包含同时存在于集合 x
和集合 y
中的元素
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
自己动手试一试 »
定义和用法
intersection()
方法返回一个包含两个或多个集合之间相似项的集合。
含义:返回的集合仅包含同时存在于两个集合中的项,如果比较的是三个或更多集合,则包含所有集合中都存在的项。
作为快捷方式,您可以使用 &
运算符代替,请参阅下面的示例。
语法
set.intersection(set1, set2 ... 等)
参数值
参数 | 描述 |
---|---|
set1 | 必需。用于查找相等元素的集合 |
set2 | 可选。要搜索相等项的另一个集合。 您可以比较任意数量的集合。 使用逗号分隔集合 |
更短的语法
set & set1 & set2 ... 等
参数值
参数 | 描述 |
---|---|
set1 | 必需。用于查找相等元素的集合 |
set2 | 可选。要搜索相等项的另一个集合。 您可以比较任意数量的集合。 使用 & (和运算符) 分隔集合。请参见下面的示例。 |
更多示例
示例
使用 &
作为 intersection()
的快捷方式
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x & y
print(z)
自己动手试一试 »
示例
合并 3 个集合,并返回一个包含这 3 个集合中都存在的项的集合
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)
自己动手试一试 »
示例
使用 &
运算符合并 3 个集合
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x & y & z
print(result)
自己动手试一试 »