兩個給定集合的並集是包含兩個集合的所有元素的最小集合。兩個給定集合A和B的並集是一個由A的所有元素和B的所有元素組成的集合,這樣就不會重複任何元素。
表示集合並集的符號是“ U”。示例:
Input:Let set A = {2, 4, 5, 6} and set B = {4, 6, 7, 8} Output:{2, 4, 5, 6, 7, 8} Explanation:Taking every element of both the sets A and B, without repeating any element, we get a new set = {2, 4, 5, 6, 7, 8}.This new set contains all the elements of set A and all the elements of set B with no repetition of elements and is named as union of set A and B.
用法:
set1.union(set2, set3, set4….)
In parameters, any number of sets can be given
返回值:
The union() function returns a set, which has the union of all sets(set1, set2, set3…) with set1.
It returns a copy of set1 only if no parameter is passed.
以下是上述方法的Python3實現:
# Python3 program for union() function
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {7, 8, 9, 10}
# union of two sets
print("set1 U set2:", set1.union(set2))
# union of three sets
print("set1 U set2 U set3:", set1.union(set2, set3))
輸出:
set1 U set2: {2, 4, 5, 6, 7, 8} set1 U set2 U set3:{2, 4, 5, 6, 7, 8, 9, 10}
實際應用:
在大多數概率問題中,需要集合並集的概念。
相關用法
- Python Pandas Index.union()用法及代碼示例
- Python Pandas TimedeltaIndex.union()用法及代碼示例
- Python oct()用法及代碼示例
- Python map()用法及代碼示例
- Python int()用法及代碼示例
- Python cmp()用法及代碼示例
- Python id()用法及代碼示例
- Python dir()用法及代碼示例
注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Union() function in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。