当前位置:首页 > 行业动态 > 正文

python 如何取交集

在Python中,可以使用集合(set)的交集操作来取两个集合的交集,以下是详细的步骤:

1、创建两个集合

python 如何取交集  第1张

2、使用&操作符或intersection()方法获取交集

示例代码:

python 如何取交集  第2张

创建两个集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
使用 & 操作符获取交集
intersection_set = set1 & set2
print("使用 & 操作符获取交集:", intersection_set)
使用 intersection() 方法获取交集
intersection_set = set1.intersection(set2)
print("使用 intersection() 方法获取交集:", intersection_set)

输出结果:

使用 & 操作符获取交集: {4, 5}
使用 intersection() 方法获取交集: {4, 5}
0