气候谚语,又名无锡站长网,鬃狮蜥
本文实例讲述了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 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论