脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python3实现计算两个数组的交集算法示例

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

2021-06-11 00:26zhenghaitian Python

这篇文章主要介绍了Python3实现计算两个数组的交集算法,结合2个实例形式总结分析了Python3针对数组的遍历、位运算以及元素的添加、删除等相关操作技巧,需要的朋友可以参考下

本文实例讲述了python3实现计算两个数组的交集算法。分享给大家供大家参考,具体如下:

问题:

给定两个数组,写一个方法来计算它们的交集。

方案一:利用collections.counter&运算,一步到位,找到 最小次数 的相同元素。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- 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]

方案二:遍历其中一个数组,发现相同元素时添加到新列表中,同时删去另一个数组中的一个相同元素

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# -*- 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程序设计有所帮助。

原文链接:https://blog.csdn.net/zhenghaitian/article/details/80896392

延伸 · 阅读

精彩推荐