當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Set intersection_update()用法及代碼示例

設置 intersection_update() 方法

intersection_update() 方法用於使用所有集合中存在的公共元素更新原始集合,即我們可以說 intersection_update() 用於刪除不需要的元素(並非在所有集合中都可用)。

用法:

    set1. intersection_update(set1, set2, set3, ...)

參數:

  • set1– 表示要與該集合進行比較的集合。
  • set2, set3, ...– 這些是可選的集合,我們可以提供多個集合進行比較。

返回值:

這個方法的返回類型是<class 'NoneType'>,它什麽都不返回。

範例1:

# Python Set intersection_update() Method with Example

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# before method call 
print("Before intersection_update() method call...")
print("cars_1:", cars_1)
print("cars_2:", cars_2)

# intersection_update() method call
cars_1.intersection_update(cars_2)

# printing the set after method call
print("After intersection_update() method call...")
print("cars_1:", cars_1)
print("cars_2:", cars_2)

輸出

Before intersection_update() method call...
cars_1:{'Lexus', 'Porsche', 'Audi'}
cars_2:{'Lincoln', 'Porsche', 'Mazda'}
After intersection_update() method call...
cars_1:{'Porsche'}
cars_2:{'Lincoln', 'Porsche', 'Mazda'}

範例2:

# Python Set intersection_update() Method with Example

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "ABC"}

# printing the results
print("x:", x)
print("y:", y)
print("z:", z)

# printing the common elements
x.intersection_update(y,z)
print("x:",x)

輸出

x:{'XYZ', 'PQR', 'ABC'}
y:{'XYZ', 'PQR', 'ABC'}
z:{'MNO', 'ABC', 'DEF'}
x: {'ABC'}


相關用法


注:本文由純淨天空篩選整理自 Python Set intersection_update() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。