[英]How to find most common element in a list of list?
我明白
a = max(set(lst), key=lst.count)
将导出列表中最常见的元素
但是如何在不使用辅助函数的情况下导出列表列表中最常见的元素?
例如
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
:
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'
或者,您可以(有点)将当前解决方案用于每个子列表:
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'
只需展平list of list
,然后使用collections.Counter
就可以了。 然后使用Counter.most_common()
方法获取元素tuple
的list
,其出现次数从高到低:-
>>> lst = [['1','2','3','4'],['1','1','1','1'],['1','2','3','4']]
>>> flattened_list = [elem for sublist in lst for elem in sublist]
>>> flattened_list
['1', '2', '3', '4', '1', '1', '1', '1', '1', '2', '3', '4']
>>>
>>> from collections import Counter
>>>
>>> counter = Counter(flattened_list)
>>> counter.most_common()
[('1', 6), ('3', 2), ('2', 2), ('4', 2)]
>>>
>>> counter.most_common(1)
('1', 6)
或者,您可以使用您的方法从flatten
列表中获取最常见的元素。
>>> max(set(flattened_list), key=flattened_list.count)
'1'
您也可以像这样扁平化您的列表:-
>>> sum(lst, [])
['1', '2', '3', '4', '1', '1', '1', '1', '1', '2', '3', '4']
因此, 作为一个单行代码,您可以这样做:-
>>> lst = [['1','2','3','4'],['1','1','1','1'],['1','2','3','4']]
>>> max(set(sum(lst, [])), key=sum(lst, []).count)
'1'
当然,最后一个创建两个具有相同内容的列表。
您必须用( chain(*lst)
)来修饰列表,然后使用Counter(chain(*lst).most_common())
计算列表中每个元素的条目,并对结果进行排序。
from itertools import chain
from collections import Counter
lst = [['1','2','3','4'],['1','1','1','1'],['1','2','3','4']]
sorted(Counter(chain(*lst)).most_common())[0][0]
您可以使用Counter
查找最常见的元素,并使用chain
来遍历列表列表中的元素:
from collections import Counter
from itertools import chain
print Counter(val for val in chain.from_iterable(lst)).most_common(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.