mg1986
mg1986

Reputation: 25

How to sort a Python list descending based on item count, but return a list with sorted items only, and not a count also?

I am generating some large lists in python, and I need to figure out the absolute fastest way to return a sort list from something like this:

myList = ['a','b','c','a','c','a']

and return a list of it in descending order, based on the count of the items, so it looks like this.

sortedList = ['a','c','b']

I have been using Counter().most_common(), but this returns a tuple in descending order with the item, and the number of times in appears in the list. I really just need a tuple or list in descending order based off count, with just the items, and not the count amounts. Any ideas?

Edit: So would doing something like this be faster?

myList = ['a','b','c','a','c','a']
count = Counter(myList).most_common()
res = [k for k,v in count]

Upvotes: 0

Views: 819

Answers (1)

Jon Clements
Jon Clements

Reputation: 142256

from collections import Counter

myList = ['a','b','c','a','c','a']
res = [k for k,v in Counter(myList).most_common()]
# ['a', 'c', 'b']

Upvotes: 5

Related Questions