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)
自己動手試一試 »