Python3實現計算兩個數組的交集算法示例
更新時間:2019年04月03日 09:26:05 作者:zhenghaitian
這篇文章主要介紹了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]
方案二:遍歷其中一個數組,發(fā)現相同元素時添加到新列表中,同時刪去另一個數組中的一個相同元素
# -*- 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執(zhí)行系統(tǒng)命令4種方法與比較
這篇文章主要介紹了python執(zhí)行系統(tǒng)命令4種方法與比較,需要的朋友可以參考下2021-04-04