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


