Terence Chow
Terence Chow

Reputation: 11153

get most common element but if frequencies match, get lower element

I've been using max(Counter(a_list_here),key=Counter(a_list_here).get) to get the most common element.

However when there are 2 elements which have matching frequencies I want to get the element that is the smallest. For example:

a= [1,2,5,5,8,8,5,7,8]

There are three 5s and three 8s. My function max(Counter(a),key=Counter(a).get) produces 8 instead of 5.

Is there anyway to do this quickly and cleanly?

I'm using python 3.2

Upvotes: 1

Views: 54

Answers (2)

Óscar López
Óscar López

Reputation: 235994

Try this, there's no need to sort it first:

from collections import Counter
a = [1,2,5,5,8,8,5,7,8]

In Python 2.7:

max(Counter(a).iteritems(), key=lambda (k,v): (v,-k))[0]
=> 5

In Python 3.x:

max(Counter(a).items(), key=lambda p: (p[1],-p[0]))[0]
=> 5

Upvotes: 1

Owen
Owen

Reputation: 1736

This may not be the fastest way, but:

sorted([x for x in a if a.count(x) > 1])[0]

>>> a= [1,2,5,5,8,8,5,7,8]
>>> sorted([x for x in a if a.count(x) > 1])[0]
5

Upvotes: 1

Related Questions