Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

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

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 in a list of list without using helper function?

For example

lst = [['1','2','3','4'],['1','1','1','1'],['1','2','3','4']]

The output should equal 1.

When I try a = max(set(lst), key=lst.count)

it writes builtins.TypeError: unhashable type: 'list'

Can anyone please help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...