在 Python 中查找二维列表中最常见的元素


二维列表以列表作为其元素。换句话说,它是一个列表的列表。在本文中,我们需要找到列表内部所有列表中最常见的元素。

使用 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)
# Given list
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("Given List:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))

输出

运行以上代码,得到以下结果:

Given List:
[[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)
# Given list
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("Given List:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))

输出

运行以上代码,得到以下结果:

Given List:
[[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]
# Given list
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("Given List:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))

输出

运行以上代码,得到以下结果:

Given List:
[[45, 20, 11], [20, 17, 45], [20, 13, 9]]
Element with highest frequency:
20

更新于: 2020年6月4日

554 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.