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.