Python 集合 intersection_update() 方法

实例

删除集合 x 和集合 y 都不存在的项目:

  1. x = {"apple", "banana", "cherry"}
  2. y = {"google", "microsoft", "apple"}
  3. x.intersection_update(y)
  4. print(x)

定义和用法

intersection_update() 方法会删除各集合中都不存在的项目。

intersection_update() 方法与 intersection() 方法不同,因为 intersection() 方法返回一个新集合,其中没有不需要的项目,而 intersection_update() 方法从原始集中删除了不需要的项目。


语法

  1. set.intersection_update(set1, set2 ... etc)
参数值
参数描述
set1必需。要在其中检索相等项目的集合。
set2

可选。要在其中检索相等项目的另一集合。

您能够比较任意多的集合。

集合由逗号分隔。


更多实例

比较 3 个集合,返回的集合包含存在于所有 3 个集合中的项目:

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

分类导航