📜  Python中的 Union()函数

📅  最后修改于: 2022-05-13 01:54:39.475000             🧑  作者: Mango

Python中的 Union()函数

Python set Union()函数返回一个新集合,其中包含原始集合中的所有项目。

两个给定集合的并集是包含两个集合的所有元素的最小集合。两个给定集合 A 和 B 的并集是由 A 的所有元素和 B 的所有元素组成的集合,使得没有元素重复。

表示集合并集的符号是“U”

例子:

Python set Union() 语法:

Python set Union() 返回值:

Python set Union() 方法的示例:

示例 1:使用Python set Union() 方法

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))


Python3
# Python3 program for union with | operator
 
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {7, 8, 9, 10}
 
# union of two sets
print("set1 U set2 : ", set1 | set2)
 
# union of three sets
print("set1 U set2 U set3 :", set1 |set2 | set3)


输出:

set1 U set2 :  {2, 4, 5, 6, 7, 8}
set1 U set2 U set3 : {2, 4, 5, 6, 7, 8, 9, 10}

示例 2:使用 | 设置联合操作员

我们可以使用“|”运算符来查找集合的并集。

Python3

# Python3 program for union with | operator
 
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {7, 8, 9, 10}
 
# union of two sets
print("set1 U set2 : ", set1 | set2)
 
# union of three sets
print("set1 U set2 U set3 :", set1 |set2 | set3)

输出:

set1 U set2 :  {2, 4, 5, 6, 7, 8}
set1 U set2 U set3 : {2, 4, 5, 6, 7, 8, 9, 10}