0

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]
2
  • 2
    Just list-comp over the most_common to only select the key? Commented May 21, 2014 at 17:17
  • sorted(counter_obj, key=counter_obj.__getitem__, reverse=True) Commented May 21, 2014 at 17:17

1 Answer 1

5
from collections import Counter

myList = ['a','b','c','a','c','a']
res = [k for k,v in Counter(myList).most_common()]
# ['a', 'c', 'b']
Sign up to request clarification or add additional context in comments.

11 Comments

Not the fastest way though, no need to introduce a Python for-loop.
@200OK Since .most_common() is sorting anyway... no need to pre-generate a Counter, then sort using its values using a look up either...
@200OK a comprehension loops at C speed so I'm not sure what your point is. The fact that comprehension grammar includes the word "for" doesn't means it performs like an actual for loop.
On a test I just ran comparing 1M choices of 'a','b','c', I got exactly 139 ms for each, so whatever minor performance differences there are probably wash out at large size anyway.
@JonClements I thought OP wanted to use the Counter later as well, if that's not the case then this is fastest solution I guess.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.