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.