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