python中用来计算集合并集的是_Python集合(set)并集

Python集合(set)并集教程

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)

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

我们使用 {} 定义了两个集合,分别为集合 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)

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

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

Python集合(set)并集总结

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

s = s1.union(s2)

使用或求集合并集语法:

s = s1 | s2

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值