Find the most common element in list of lists

一曲冷凌霜 提交于 2021-02-10 17:44:09

问题


This is my list

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

I wanna find most common elemments. I have tried this

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() 

but it works just for simple list. my output should be like this

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

回答1:


Apply Counter().update() option on the elements of your list, Based on suggestion from @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()

output:

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



回答2:


itertools.chain.from_iterable

collections.Counter accepts any iterable of hashable elements. So you can chain your list of lists via itertools.chain. The benefit of this solution is it works for any number of sublists.

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)]


来源:https://stackoverflow.com/questions/53515649/find-the-most-common-element-in-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!