python并集符号_Python Union()用法及代码示例

两个给定集合的并集是包含两个集合的所有元素的最小集合。两个给定集合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}

实际应用:

在大多数概率问题中,需要集合并集的概念。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值