How to find most common element in a list of list?

前端 未结 4 1835
梦毁少年i
梦毁少年i 2020-12-19 23:13

I understand

a = max(set(lst), key=lst.count)

will derive most common element in a list

but how do you derive most common element

4条回答
  •  悲&欢浪女
    2020-12-19 23:32

    You have to flattern your list (with chain(*lst)), then count entry of each element of your list with Counter(chain(*lst).most_common()) and sort the result.

    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]
    

提交回复
热议问题