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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python实现简单socket程序在两台电脑之间传输消息的方法

本文实例讲述了python实现简单socket程序在两台电脑之间传输消息的方法。分享给大家供大家参考。具体分析如下: python开发简单socket程序在两台电脑之间传输消息,分为客户...

Pandas之drop_duplicates:去除重复项方法

Pandas之drop_duplicates:去除重复项方法

方法 DataFrame.drop_duplicates(subset=None, keep='first', inplace=False) 参数 这个drop_duplicate...

python中tkinter的应用:修改字体的实例讲解

python中tkinter的应用:修改字体的实例讲解

参考链接:tkinter book font字体的参数有如下6个 family: 字体类别,如'Fixdsys' size: 作为一个整数,以点字体的高度。为了获得字体的n个像素高,使用...

opencv 获取rtsp流媒体视频的实现方法

获取实时数据 import cv2 # user: admin # pwd: 12345 # main: 主码流 # ip: 192.168.1.64 # Channels: 实时...

python实现数据清洗(缺失值与异常值处理)

python实现数据清洗(缺失值与异常值处理)

1。 将本地sql文件写入mysql数据库 本文写入的是python数据库的taob表 source [本地文件] 其中总数据为9616行,列分别为title,link,pric...