在 Python 中查找二维列表中最常见的元素
pythonserver side programmingprogramming更新于 2026/1/22 17:16:17
二维列表以列表为元素。换句话说,它是一个列表的列表。在本文中,我们需要找到列表中所有列表中最常见的元素。
使用 max 和 count
我们设计了一个带有 in 条件的后续操作来检查给定子列表中是否存在元素。然后我们应用 max 函数和 count 函数来获取频率最高的元素。
示例
def highest_freq(lst):
SimpleList = [el for sublist in lst for el in sublist]
return max( SimpleList, key= SimpleList.count)
# 给定列表
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("给定列表:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))
输出
运行上述代码得到以下结果 −
给定列表: [[45, 20, 11], [20, 17, 45], [20, 13, 9]] Element with highest frequency: 20
使用 chain
这里我们采用与上面类似的方法。但我们使用 itertools 模块中的 chain 函数。
示例
from itertools import chain
def highest_freq(lst):
SimpleList = list(chain.from_iterable(lst))
return max( SimpleList, key= SimpleList.count)
# 给定列表
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("给定列表:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))
输出
运行上述代码得到以下结果 −
给定列表: [[45, 20, 11], [20, 17, 45], [20, 13, 9]] Element with highest frequency: 20
使用 Counter 和 chain
在此方法中,collections 中的 counter 函数会保留使用 itertools 中的 chain 函数检索到的元素的计数。
示例
from itertools import chain
from collections import Counter
def highest_freq(lst):
SimpleList = chain.from_iterable(lst)
return Counter(SimpleList).most_common(1)[0][0]
# 给定列表
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("给定列表:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))
输出
运行上述代码得到以下结果 −
给定列表: [[45, 20, 11], [20, 17, 45], [20, 13, 9]] Element with highest frequency: 20
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

