Python3计算两个数组交集的两种实现方法
本文介绍Python3中计算两个数组交集的两种常见方案。第一种利用collections.Counter与交集运算符一步获取结果;第二种通过遍历并动态删除元素实现。文章包含完整代码示例及运行结果,适合Python开发者参考。
Python3数组交集算法示例
本文分享一个使用Python3计算两个数组交集的具体算法示例,供学习参考。
问题描述
给定两个整数数组,编写一个函数来计算它们的交集。
方案一:利用collections.Counter的&运算,一步到位,找到最小次数的相同元素。
# -*- coding:utf-8 -*-
#! python3
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
import collections
a, b = map(collections.Counter, (nums1, nums2))
return list((a & b).elements())
#测试
arr1 = [1,2,3,4,5]
arr2 = [3,4,5,6,7]
print(intersect(arr1,arr2))
运行结果:
[3, 4, 5]
方案二:遍历其中一个数组,发现相同元素时添加到新列表中,同时删去另一个数组中的一个相同元素。
# -*- coding:utf-8 -*-
#! python3
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
for k in nums1:
if k in nums2:
res.append(k)
nums2.remove(k)
return res
#测试
arr1 = [1,2,3,4,5]
arr2 = [3,4,5,6,7]
print(intersect(arr1,arr2))
运行结果:
[3, 4, 5]
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













