python怎么求交集和并集

   2025-02-13 9410
核心提示:Python中,可以使用set()函数将一个列表转换为集合。然后使用交集和并集操作符来求交集和并集。下面是一个示例代码:# 定义两个

Python中,可以使用set()函数将一个列表转换为集合。然后使用交集和并集操作符来求交集和并集。下面是一个示例代码:

# 定义两个列表list1 = [1, 2, 3, 4, 5]list2 = [4, 5, 6, 7, 8]# 将列表转换为集合set1 = set(list1)set2 = set(list2)# 求交集intersection = set1 & set2print("交集:", intersection)# 求并集union = set1 | set2print("并集:", union)

输出结果为:

交集: {4, 5}并集: {1, 2, 3, 4, 5, 6, 7, 8}

另外,还可以使用set()函数直接将列表转换为集合,并使用intersection()和union()函数求交集和并集,示例如下:

# 定义两个列表list1 = [1, 2, 3, 4, 5]list2 = [4, 5, 6, 7, 8]# 将列表转换为集合set1 = set(list1)set2 = set(list2)# 求交集intersection = set1.intersection(set2)print("交集:", intersection)# 求并集union = set1.union(set2)print("并集:", union)

输出结果与前面相同。

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