user10702710
user10702710

Reputation:

Find the most common element in list of lists

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

Upvotes: 1

Views: 3603

Answers (2)

Venkatachalam
Venkatachalam

Reputation: 16966

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

Upvotes: 3

jpp
jpp

Reputation: 164843

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

Upvotes: 2

Related Questions