Python集合(set)并集

Python集合(set)并集教程

Python集合 的并集用于计算两个集合的所有拥有的元素,在 Python 中,计算集合并集有两种方法,分别为:使用 union 函数和使用或符号。

union 求集合并集详解

语法

s = s1.union(s2)

参数

参数 描述
s1 需要求并集的集合。
s2 需要求并集的集合。
s 求得并集的结果。

返回值

返回并集的结果。

说明

求集合 s1 和集合 s2 的并集,并将并集的结果赋值给集合 s。

或 | 求集合并集详解

语法

s = s1 | s2

参数

参数 描述
s1 需要求并集的集合。
s2 需要求并集的集合。
s 求得并集的结果。

说明

求集合 s1 和集合 s2 的并集,并将并集的结果赋值给集合 s。

案例

使用 union 求集合并集

用 union 求集合并集,并集结果通过返回值返回

print("嗨客网(www.haicoder.net)") # 用 union 求集合并集,并集结果通过返回值返回 s1 = {"Hello", "HaiCoder", 1024} s2 = {"HaiCoder", "Python", "Golang"} union_s = s1.union(s2) print("S1 =", s1) print("S2 =", s2) print("union_s =", union_s)

程序运行后,控制台输出如下:

146 python集合set并集.png

我们使用 {} 定义了两个集合,分别为集合 s1 和集合 s2,接着,我们使用集合内置的函数 union 求集合 s1 和集合 s2 的并集,并将求的并集的结果赋值给集合 union_s

最后,我们发现,集合 s1 和集合 s2 的并集元素被存放到了集合 union_s 中。

使用或求集合并集

使用或求集合并集,并集结果通过返回值返回

print("嗨客网(www.haicoder.net)") # 使用或求集合并集,并集结果通过返回值返回 s1 = {"Hello", "HaiCoder", 1024} s2 = {"HaiCoder", "Python", "Golang"} union_s = s1 | s2 print("S1 =", s1) print("S2 =", s2) print("union_s =", union_s)

程序运行后,控制台输出如下:

147 python集合set并集.png

我们使用 {} 定义了两个集合,分别为集合 s1 和集合 s2,接着,我们使用或符号,即 | 求集合 s1 和集合 s2 的并集,并将求的并集的结果赋值给集合 union_s

Python集合(set)并集总结

Python 的集合的并集用于计算两个集合的所有拥有的元素,在 Python 中,计算集合并集有两种方法,分别为:使用 union 函数和使用或符号。使用 union 求集合并集语法:

s = s1.union(s2)

使用或求集合并集语法:

s = s1 | s2