网络编程
位置:首页>> 网络编程>> Python编程>> Python3实现计算两个数组的交集算法示例

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

作者:zhenghaitian  发布时间:2021-06-03 00:21:19 

标签: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程序设计有所帮助。

来源:https://blog.csdn.net/zhenghaitian/article/details/80896392

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com