在 Python 中通过字典交集查找三个排序数组中的公共元素
pythonserver side programmingprogramming更新于 2025/10/11 10:20:17
在使用 Python 处理数据时,我们可能会遇到需要查找多个数组中公共元素的情况。这可以通过将数组转换为字典来实现,如下所示。
在下面的示例中,我们获取数组并应用来自 collections 模块的 Counter 容器。它将保存容器中每个元素的计数。然后,我们通过应用 dict() 并使用 & 运算符将它们转换为字典,以仅识别数组中的公共元素。最后,我们循环遍历新创建的字典的项目,并附加字典中的值,以获得最终的公共值结果。
示例
from collections import Counter
arrayA = ['Sun', 12, 14, 11, 34]
arrayB = [6, 12, 'Sun', 11]
arrayC = [19, 6, 20, 'Sun', 12, 67, 11]
arrayA = Counter(arrayA)
arrayB = Counter(arrayB)
arrayC = Counter(arrayC)
# 交集
commonDict = dict(arrayA.items() & arrayB.items() & arrayC.items())
res = []
# 结果
for (key, val) in commonDict.items():
for i in range(0, val):
res.append(key)
print("The common values among the arrays are:\n ",res)
输出
运行上述代码得到以下结果 −
The common values among the arrays are: ['Sun', 11, 12]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

