Python3实现计算两个数组的交集算法示例

这篇文章主要介绍了Python3实现计算两个数组的交集算法,结合2个实例形式总结分析了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学习扣qun:913066266 ,看看前辈们是如何学习的!从基础的python脚本到web开发、爬虫、django、数据挖掘等【PDF,实战源码】,零基础到项目实战的资料都有整理。送给每一位python的小伙伴!每天都有大牛定时讲解Python技术,分享一些学习的方法和需要注意的小细节,点击加入我们的 python学习者聚集地

发布了47 篇原创文章 · 获赞 53 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/haoxun03/article/details/104270609