Linux 拨号vps windows公众号手机端

python怎么求交集和并集

lewis 8年前 (2017-05-19) 阅读数 7 #程序编程
文章标签 python

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

# 定义两个列表
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

# 将列表转换为集合
set1 = set(list1)
set2 = set(list2)

# 求交集
intersection = set1 & set2
print("交集:", intersection)

# 求并集
union = set1 | set2
print("并集:", 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)

输出结果与前面相同。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门