如何在列表列表中找到最常见的元素? [英] How to find most common element in a list of list?
本文介绍了如何在列表列表中找到最常见的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我了解
a = max(set(lst), key=lst.count)
将导出列表中最常见的元素
will derive most common element in a list
但是如何在不使用辅助函数的情况下导出列表列表中最常见的元素?
but how do you derive most common element in a list of list without using helper function?
例如
lst = [['1','2','3','4'],['1','1','1','1'],['1','2','3','4']]
输出应等于1
.
当我尝试a = max(set(lst), key=lst.count)
它写builtins.TypeError: unhashable type: 'list'
有人可以帮助我吗?
推荐答案
有很多方法,但是我想让您知道,标准模块中有一些不错的工具可以解决这类问题,例如 collections.Counter
:
There are many ways, but I wanted to let you know that there are some nice tools for that kind of things in the standard modules, e.g. collections.Counter
:
In [1]: lst = [['1','2','3','4'],['1','1','1','1'],['1','2','3','4']]
In [2]: from collections import Counter
In [3]: from operator import itemgetter
In [4]: max((Counter(l).most_common(1)[0] for l in lst), key=itemgetter(1))[0]
Out[4]: '1'
或者,您可以(有点)将当前解决方案应用于每个子列表:
Or, you could (kinda) employ your current solution for each of the sublists:
In [5]: max(((max(set(l), key=l.count), l) for l in lst),
...: key=lambda x: x[1].count(x[0]))[0]
Out[5]: '1'
这篇关于如何在列表列表中找到最常见的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文