Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > Python编程技巧

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

来源:中文源码网    浏览:108 次    日期:2024-05-15 04:11:31
【下载文档:  Python3实现计算两个数组的交集算法示例.txt 】


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相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。

相关内容