python

python怎么求交集和并集

小亿
115
2023-12-26 21:28:05
栏目: 编程语言

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)

输出结果与前面相同。

0
看了该问题的人还看了