温馨提示×

Set在Python如何合并两个集合

小樊
191
2024-08-02 22:53:10
栏目: 编程语言

在Python中,可以使用union()方法或者|操作符来合并两个集合。

示例代码:

set1 = {1, 2, 3} set2 = {3, 4, 5} # 使用union()方法合并两个集合 merged_set = set1.union(set2) print(merged_set) # 输出{1, 2, 3, 4, 5} # 使用|操作符合并两个集合 merged_set = set1 | set2 print(merged_set) # 输出{1, 2, 3, 4, 5} 

以上代码中,我们首先定义了两个集合set1和set2,然后使用union()方法和|操作符将两个集合合并成一个新的集合merged_set。

0