跳到主要内容

Python 集合 intersection_update() 方法

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

示例

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

# 将集合 A 更新为 A 和 B 的共同项
A.intersection_update(B)

print('A =', A)

# 输出: A = {2, 3, 4}

intersection_update() 语法

intersection_update() 方法的语法是:

A.intersection_update(*sets)

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

intersection_update() 参数

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

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

例如,

A.intersection_updata(B, C)

这里,方法有两个参数,B 和 C。

intersection_update() 返回值

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

示例:Python 集合 intersection_update()

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

# 在 A、B 和 C 之间执行交集运算,并将结果更新到集合 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() 来计算集合 A、B 和 C 之间的交集。交集的结果更新到集合 A。

这就是为什么我们得到 A = {4} 作为输出,因为 4 是唯一一个同时存在于所有三个集合中的项。而集合 B 和 C 保持不变。