python set运算如何实现集合的交集

   2024-10-01 4270
核心提示:在Python中,可以使用set()函数或者集合对象的intersection()方法来计算两个集合的交集。以下是使用set()函数的示例:# 定义两个

在Python中,可以使用set()函数或者集合对象的intersection()方法来计算两个集合的交集。

以下是使用set()函数的示例:

# 定义两个集合set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 计算交集intersection_set = set1 & set2print(intersection_set)  # 输出: {3, 4}

以下是使用intersection()方法的示例:

# 定义两个集合set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 计算交集intersection_set = set1.intersection(set2)print(intersection_set)  # 输出: {3, 4}

还可以使用intersection()方法同时计算多个集合的交集:

# 定义三个集合set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}set3 = {3, 4, 7, 8}# 计算交集intersection_set = set1.intersection(set2, set3)print(intersection_set)  # 输出: {3, 4}

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

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