在本教程中,我們將借助示例了解 Python Set union() 方法。
Python set union()
方法返回一個新集合,其中包含來自所有集合的不同元素。
示例
A = {2, 3, 5}
B = {1, 3, 5}
# compute union between A and B
print('A U B = ', A.union(B))
# Output: A U B = {1, 2, 3, 5}
用法:
用法:
A.union(*other_sets)
注意: *不是語法的一部分。它用於指示該方法可以采用 0 個或多個參數。
返回:
union()
方法返回一個新集合,其中包含來自集合和所有其他集合的元素(作為參數傳遞)。- 如果參數未傳遞給
union()
,則返回集合的淺拷貝。
示例 1:Python 集 union()
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C = {1, 2, 3}
print('A U B =', A.union(B))
print('B U C =', B.union(C))
print('A U B U C =', A.union(B, C))
print('A.union() =', A.union())
輸出
A U B = {2, 'a', 'd', 'c'}
B U C = {1, 2, 3, 'd', 'c'}
A U B U C = {1, 2, 3, 'a', 'd', 'c'}
A.union() = {'a', 'd', 'c'}
Set Union 的工作
兩個或多個集合的並集是所有集合中存在的所有不同元素的集合。例如:
A = {1, 2} B = {2, 3, 4} C = {5} Then, A∪B = B∪A = {1, 2, 3, 4} A∪C = C∪A = {1, 2, 5} B∪C = C∪B = {2, 3, 4, 5} A∪B∪C = {1, 2, 3, 4, 5}

示例 2:使用 | 設置聯合操作符
您還可以使用 |
運算符找到集合的並集。
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C = {1, 2, 3}
print('A U B =', A| B)
print('B U C =', B | C)
print('A U B U C =', A | B | C)
輸出
A U B = {2, 'a', 'c', 'd'} B U C = {1, 2, 3, 'c', 'd'} A U B U C = {1, 2, 3, 'a', 'c', 'd'}
相關用法
- Python Set update()用法及代碼示例
- Python Set issuperset()用法及代碼示例
- Python Set difference_update()用法及代碼示例
- Python Set pop()用法及代碼示例
- Python Set add()用法及代碼示例
- Python Set clear()用法及代碼示例
- Python Set issubset()用法及代碼示例
- Python Set isdisjoint()用法及代碼示例
- Python Set intersection_update()用法及代碼示例
- Python Set symmetric_difference()用法及代碼示例
- Python Set symmetric_difference_update()用法及代碼示例
- Python Set discard()用法及代碼示例
- Python Set intersection()用法及代碼示例
- Python Set copy()用法及代碼示例
- Python Set difference()用法及代碼示例
- Python Set remove()用法及代碼示例
- Python Set轉String用法及代碼示例
- Python Pandas Series.cumsum()用法及代碼示例
- Python Pandas Series.astype()用法及代碼示例
- Python Pandas Series.nonzero()用法及代碼示例
注:本文由純淨天空篩選整理自 Python Set union()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。