python求并集的方法是什么

   2025-02-13 3020
核心提示:在Python中,可以使用以下方法来求两个集合的并集:使用|运算符:可以通过将两个集合用|运算符连接起来,得到它们的并集。例如:

在Python中,可以使用以下方法来求两个集合的并集:

使用|运算符:可以通过将两个集合用|运算符连接起来,得到它们的并集。例如:
set1 = {1, 2, 3}set2 = {3, 4, 5}union_set = set1 | set2print(union_set)  # 输出:{1, 2, 3, 4, 5}
使用union()方法:union()方法可以将一个集合与另一个集合求并集。例如:
set1 = {1, 2, 3}set2 = {3, 4, 5}union_set = set1.union(set2)print(union_set)  # 输出:{1, 2, 3, 4, 5}

无论是使用|运算符还是union()方法,都能得到两个集合的并集。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言