Python Set union() 方法
描述
union() 方法返回兩個集合的並集,即包含了所有集合的元素,重複的元素只會出現一次。
語法
union() 方法語法:
set.union(set1, set2...)
參數
- set1 -- 必需,合併的目標集合
- set2 -- 可選,其他要合併的集合,可以多個,多個使用逗號 , 隔開。
返回值
返回一個新集合。
實例
合併兩個集合,重複元素只會出現一次:
實例 1
x = {"apple", "banana", "cherry"}
y = {"google", "zaixian", "apple"}
z = x.union(y)
print(z)
輸出結果為:
{'cherry', 'zaixian', 'google', 'banana', 'apple'}
合併多個集合:
實例 1
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
result = x.union(y, z)
print(result)
輸出結果為:
{'c', 'd', 'f', 'e', 'b', 'a'}