上一篇
python 如何取交集
- 行业动态
- 2024-04-08
- 6
在Python中,可以使用集合(set)的交集操作来取两个集合的交集,以下是详细的步骤:
1、创建两个集合
2、使用&
操作符或intersection()
方法获取交集
示例代码:
创建两个集合 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}