python

Python set()函数的并集操作

小樊
93
2024-08-02 08:08:09
栏目: 编程语言

set()函数用于创建一个集合,集合是一个无序且不重复的元素集合。可以使用|操作符或union()方法来计算两个集合的并集。

下面是一个示例代码:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

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

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

输出结果为:

{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

0
看了该问题的人还看了