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


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

設置 union() 方法

union() 方法用於查找所有集合的並集,使用此集合調用此方法(set1) 和其他集合 (set1, set2, ...) 可以作為參數提供,方法返回包含所有集合的所有元素的集合(公共元素隻重複一次)。

用法:

    set1.union(set2, set3, ...)

參數:

  • set2, set3, ...——這裏,set2是必需的,其他集是可選的。

返回值:

這個方法的返回類型是<class 'set'>,它返回所有元素的集合。

範例1:

# Python Set union() Method with Example

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

# finding the union of both sets
x = cars_1.union(cars_2)

# print the set
print("cars_1:", cars_1)
print("cars_2:", cars_2)
print("x:", x)

輸出

cars_1: {'Porsche', 'Audi', 'Lexus'}
cars_2: {'Porsche', 'Mazda', 'Lincoln'}
x: {'Porsche', 'Mazda', 'Lincoln', 'Audi', 'Lexus'}

範例2:

# Python Set union() Method with Example

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

# finding the union of all sets

result = x.union(y,z)

# printing the sets
print("x:", x)
print("y:", y)
print("result:", result)

輸出

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


相關用法


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