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

时间:2018-11-28 09:02:28

标签: python python-3.x list dictionary counter

这是我的清单

a=[ ['a','b','a','a'],
    ['c','c','c','d','d','d']]

我想找到最常见的元素。 我已经尝试过

from collections import Counter
words = ['hello', 'hell', 'owl', 'hello', 'world', 'war', 'hello', 
         'war','aa','aa','aa','aa']

counter_obj = Counter(words)

counter_obj.most_common() 

,但仅适用于简单列表。 我的输出应该是这样

[('a', 3), ('c', 3), ('d', 3), ('b', 1)]

2 个答案:

答案 0 :(得分:1)

在列表的元素上应用Counter().update()选项, 根据@BlueSheepToken的建议

from collections import Counter

words = [['a','b','a','a'],['c','c','c','d','d','d']]
counter = Counter(words[0])
for i in words[1:]: 
    counter.update(i)

counter.most_common()

输出:

[('a', 3), ('c', 3), ('d', 3), ('b', 1)]

答案 1 :(得分:1)

itertools.chain.from_iterable

collections.Counter接受任何可迭代的可哈希元素。因此,您可以通过itertools.chain链接列表列表。此解决方案的好处是它适用于任意数量的子列表。

from collections import Counter
from itertools import chain

counter_obj = Counter(chain.from_iterable(a))

print(counter_obj.most_common())

[('a', 3), ('c', 3), ('d', 3), ('b', 1)]