Python Set intersection_update() 方法

Python3 列表 Python 集合


描述

intersection_update() 方法用於獲取兩個或更多集合中都重疊的元素,即計算交集。

intersection_update() 方法不同於 intersection() 方法,因為 intersection() 方法是返回一個新的集合,而 intersection_update() 方法是在原始的集合上移除不重疊的元素。

語法

intersection_update() 方法語法:

set.intersection_update(set1, set2 ... etc)

參數

  • set1 -- 必需,要查找相同元素的集合
  • set2 -- 可選,其他要查找相同元素的集合,可以多個,多個使用逗號 , 隔開

返回值

無。

實例

返回一個新集合,該集合的元素既包含在集合 x 又包含在集合 y 中:

實例 1

x = {"apple", "banana", "cherry"} y = {"google", "zaixian", "apple"} x.intersection_update(y) print(x)

輸出結果為:

{'apple'}

計算多個集合的並集:

實例 1

x = {"a", "b", "c"} y = {"c", "d", "e"} z = {"f", "g", "c"} x.intersection_update(y, z) print(x)

輸出結果為:

{'c'}

Python3 列表 Python 集合