Python Set intersection_update()

intersection_update() 方法查找不同集合的交集,并将其更新到调用该方法的集合中。

示例

A = {1, 2, 3, 4}
B = {2, 3, 4, 5}

# updates set A with the items common to both sets A and B A.intersection_update(B)
print('A =', A) # Output: A = {2, 3, 4}

intersection_update() 语法

intersection_update() 方法的语法是

A.intersection_update(*sets)

这里,*sets 表示集合 A 可以与一个或多个集合求交集。


intersection_update() 参数

intersection_update() 方法允许任意数量的参数

  • *sets - 表示该方法可以接受一个或多个参数

例如,

A.intersection_updata(B, C)

这里,该方法有两个参数,BC


intersection_update() 返回值

intersection_update() 方法不返回任何值。


示例:Python Set intersection_update()

A = {1, 2, 3, 4}
B = {2, 3, 4, 5, 6}
C = {4, 5, 6, 9, 10}

# performs intersection between A, B and C and updates the result to set A A.intersection_update(B, C)
print('A =', A) print('B =', B) print('C =', C)

输出

A = {4}
B = {2, 3, 4, 5, 6}
C = {4, 5, 6, 9, 10}

在上面的示例中,我们使用 intersection_update() 计算集合 ABC 之间的交集。交集结果会更新到集合 A 中。

这就是为什么我们得到 A = {4} 作为输出,因为 4 是所有三个集合中都存在的唯一元素。而集合 BC 保持不变。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战