Python 集合 intersection() 方法



Python 集合的 intersection() 方法用于查找两个或多个集合之间的公共元素。它返回一个新集合,其中仅包含所有正在比较的集合中都存在的元素。此函数可以在集合上调用,并传递一个或多个集合作为参数。

或者,可以使用 & 运算符来获得相同的结果。

语法

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

set1.intersection(*others)

参数

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

返回值

此方法返回一个新集合,其中包含所有指定集合的公共元素。

示例 1

以下是如何执行搜索操作的示例,该操作被隐式地用于查找解释器中的公共元素,并将其作为集合返回给相应的引用:

set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = {'p','o','i','n','t'}
set_3 = {'t','u','t'}
#intersection of two sets
print("set1 intersection set2 : ", set_1.intersection(set_2))
# intersection of three sets
print("set1 intersection set2 intersection set3 :", set_1.intersection(set_2,set_3))

输出

set1 intersection set2 :  {'o', 'i', 't'}
set1 intersection set2 intersection set3 : {'t'}

示例 2

在此示例中,我们使用 lambda 表达式为元素选择创建内联函数,并借助 filter 函数检查元素是否同时包含在两个列表中:

def interSection(arr1,arr2): # finding common elements

    # using filter method to find identical values via lambda function
    values = list(filter(lambda x: x in arr1, arr2))
    print ("Intersection of arr1 & arr2 is: ",values)

# Driver program
if __name__ == "__main__":
   arr1 = ['t','u','t','o','r','i','a','l']
   arr2 = ['p','o','i','n','t']
   interSection(arr1,arr2)

输出

Intersection of arr1 & arr2 is:  ['o', 'i', 't']

示例 3

在此示例中,& 运算符用于查找集合的交集:

# Define two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

# Find the intersection using the & operator
intersection_set = set1 & set2

# Print the result
print(intersection_set)  # Output: {3, 4, 5}

输出

{3, 4, 5}

示例 4

当我们在非空集合和空集合之间执行交集时,结果将为空集合。在此示例中,我们使用 intersection() 方法执行交集:

set1 = {1, 2, 3}
set2 = set()

# Find the intersection
intersection_set = set1.intersection(set2)

# Print the result
print(intersection_set)  # Output: set()

输出

set()
python_set_methods.htm
广告

© . All rights reserved.