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

前端 未结 4 1836
梦毁少年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:37

    There are many ways, but I wanted to let you know that there are some nice tools for that kind of things in the standard modules, e.g. collections.Counter:

    In [1]: lst = [['1','2','3','4'],['1','1','1','1'],['1','2','3','4']]
    In [2]: from collections import Counter
    In [3]: from operator import itemgetter
    In [4]: max((Counter(l).most_common(1)[0] for l in lst), key=itemgetter(1))[0]
    Out[4]: '1'
    

    Or, you could (kinda) employ your current solution for each of the sublists:

    In [5]: max(((max(set(l), key=l.count), l) for l in lst),
       ...: key=lambda x: x[1].count(x[0]))[0]
    Out[5]: '1'
    

提交回复
热议问题