Tutorial Study Image

Python intersection_update()

Python 中的 intersection_update() 函数有助于集合更新。它首先找出给定集合的交集。然后用集合交集的结果元素更新第一个集合。集合交集会产生一个包含所有给定集合中共同元素的新集合。


A.intersection_update(*other_sets) #where A is a set of any iterables, like strings, lists, and dictionaries
 

intersection_update() 参数

intersection_update() 函数可以接受多个集合参数进行比较(* 表示),并用逗号分隔集合。

 

参数 描述 必需/可选
A 要在其中搜索相同项并更新的集合 必需
其他集合 要搜索相同项的另一个集合 可选

intersection_update() 返回值

此方法不返回任何值。它会更新原始集合。

result = A.intersection_update(B, C) 考虑这个例子,这里 result 将是 None。A 将是 A、B、C 的交集。B 和 C 保持不变。

Python 中 intersection_update() 方法的示例

示例 1:intersection_update() 在 Python 中如何工作?


A = {'a', 'b', 'c', 'd'}
B = {'c', 'e', 'f', 'a'}
result = A.intersection_update(B)
print('result =', result)
print('A =', A)
print('B =', B)
 

输出


result = None
A = {'a', 'c'}
B = {'c', 'e', 'f', 'a'}

示例 2:Python 方法 intersection_update() 带有两个参数


A = {'a', 'b', 'c', 'd'}
B = {'c', 'e', 'f', 'a'}
C = {'d', 'f', 'a', 'g'}
result = C.intersection_update(B, A)

print('result =', result)
print('C =', C)
print('B =', B)
print('A =', A)
 

输出


result = None
C = {'a'}
B = {'c', 'e', 'f', 'a'}
A = {'a', 'b', 'c', 'd'}