Python Set intersection_update() 方法用于更新具有自身与一个或多个其他集合交集的集合。这意味着它会修改原始集以仅包含所有涉及的集中存在的元素。
它执行就地交集操作,这比创建新集更有效。此方法可用于根据 Set 与其他 Set 共享的公共元素筛选 Set。
语法
以下是 Python Set intersection_update() 方法的语法和参数 -
set.intersection_update(*others)
参数
此函数接受可变数量的 set 对象作为参数。
返回值
此方法返回更新的集,其中包含所有指定集共有的元素。
示例 1
下面是一个示例,其中通过解释器隐式搜索以查找公共元素,并作为一组返回给相应的引用 -
def commonEle(arr):
# initialize res with set(arr[0])
res = set(arr[0])
# new value will get updated each time function is executed
for curr in arr[1:]: # slicing
res.intersection_update(curr)
return list(res)
# Driver code
if __name__ == "__main__":
nest_list=[['t','u','o','r','i','a','l'], ['p','o','i','n','t'], ['t','u','o','r','i','a','l'], ['p','y','t','h','o','n']]
out = commonEle(nest_list)
if len(out) > 0:
print (out)
else:
print ('No Common Elements')
输出
['o', 't']
示例 2
正如我们可以在两个集合上执行交集并在第一个集合中更新结果一样,我们也可以在多个集合上执行相同的方式。此示例是关于在三个集合上应用 intersection_update() 方法 -
# Define three sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6}
set3 = {4, 5, 6, 7}
# Update set1 to keep only elements present in set2 and set3
set1.intersection_update(set2, set3)
# Print the updated set1
print(set1) # Output: {4, 5}
输出
{4, 5}
示例 3
在此示例中,我们在非空集和空集上执行交集,这将产生空集 -
# Define a non-empty set and an empty set
set1 = {1, 2, 3}
set2 = set()
# Update set1 to keep only elements present in both sets
set1.intersection_update(set2)
# Print the updated set1
print(set1) # Output: set()
输出
set()
示例 4
现在,在这个例子中,我们将 intersect_update() 方法应用于一个集合和一个列表,它以集合的形式给出结果 -
# Define a set and a list
set1 = {1, 2, 3, 4, 5}
list1 = [3, 4, 5, 6, 7]
# Update set1 to keep only elements present in both set1 and list1
set1.intersection_update(list1)
# Print the updated set1
print(set1) # Output: {3, 4, 5}
输出
{3, 4, 5}