Python 集合 intersection_update() 方法



Python 集合intersection_update() 方法用于更新一个集合,使其包含自身与一个或多个其他集合的交集。这意味着它会修改原始集合,使其只包含所有参与集合中都存在的元素。

它执行就地交集操作,这比创建一个新集合更高效。此方法对于根据与其他集合共享的公共元素来筛选集合非常有用。

语法

以下是 Python 集合intersection_update() 方法的语法和参数:

set.intersection_update(*others)

参数

此函数接受可变数量的集合对象作为参数。

返回值

此方法返回更新后的集合,其中包含所有指定集合中共同的元素。

示例 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

现在,在这个例子中,我们在一个集合和一个列表上应用intersection_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}
python_set_methods.htm
广告
© . All rights reserved.