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學習者聚集地

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章