问题
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