Take a list, sort by popularity and then remove duplicates

Possible duplicate:
In python, how do I take the highest occurrence of something on a list and sort it that way?

Hello to all,

I am looking for an easy way to sort a list by popularity and then remove duplicate items.

For example, given the list:

[8, 8, 1, 1, 5, 8, 9] 

Then I would get a list similar to the following:

 [8, 1, 5, 9] 
+6
python
source share
2 answers

@SilentGhost has a great solution for Python 2.7+. A relatively simple solution for version 2.6 and later:

 a = [8, 8, 1, 1, 5, 8, 9] popularity = sorted(set(a), key=lambda x: -a.count(x)) [8, 1, 5, 9] 

This solution, however, is expensive (due to count ).

Here's another, better solution with a temporary dictionary:

 a = [8, 8, 1, 1, 5, 8, 9] d = {} for i in a: d[i] = d.get(i, 0) + 1 popularity = sorted(d, key=d.get, reverse=True) 
+12
source share
 >>> lst = [1, 1, 3, 3, 5, 1, 9] >>> from collections import Counter >>> c = Counter(lst) >>> [i for i, j in c.most_common()] [1, 3, 5, 9] 

see collections.Counter docs for links to version-compatible versions.

+13
source share

All Articles