温馨提示×

python set运算如何实现集合的并集

小樊
89
2024-08-27 11:02:02
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用set类型来表示集合。要计算两个集合的并集,可以使用union()方法或者"|"操作符。

下面是一个例子:

# 定义两个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 使用union()方法计算并集
union_set = set1.union(set2)
print("使用union()方法计算并集:", union_set)

# 使用"|"操作符计算并集
union_set = set1 | set2
print("使用'|'操作符计算并集:", union_set)

输出结果:

使用union()方法计算并集: {1, 2, 3, 4, 5, 6}
使用'|'操作符计算并集: {1, 2, 3, 4, 5, 6}

这个例子中,我们定义了两个集合set1和set2,然后使用union()方法和"|"操作符分别计算它们的并集。最后输出的结果为{1, 2, 3, 4, 5, 6}。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python set怎样实现集合运算

0