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)
这里,该方法有两个参数,B 和 C。
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()
计算集合 A、B 和 C 之间的交集。交集结果会更新到集合 A 中。
这就是为什么我们得到 A = {4}
作为输出,因为 4 是所有三个集合中都存在的唯一元素。而集合 B 和 C 保持不变。
另请阅读