如何用set()函数实现交集、并集操作

   2024-09-30 3200
核心提示:在Python中,可以使用内置的set()函数和一些其他方法来实现交集(intersection)和并集(union)操作。首先,创建两个集合

在Python中,可以使用内置的set()函数和一些其他方法来实现交集(intersection)和并集(union)操作。

首先,创建两个集合:

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

接下来,我们将使用set()函数和其他方法来计算这两个集合的交集和并集。

交集(Intersection):要计算两个集合的交集,可以使用&运算符或者intersection()方法。

使用&运算符:

intersection_set = set1 & set2print("Intersection using '&' operator:", intersection_set)

使用intersection()方法:

intersection_set = set1.intersection(set2)print("Intersection using 'intersection()' method:", intersection_set)
并集(Union):要计算两个集合的并集,可以使用|运算符或者union()方法。

使用|运算符:

union_set = set1 | set2print("Union using '|' operator:", union_set)

使用union()方法:

union_set = set1.union(set2)print("Union using 'union()' method:", union_set)

上述代码将分别输出交集和并集的结果。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号