Home > database >  How do I sort this list by frequency, this is what I've tried and its not what I expected
How do I sort this list by frequency, this is what I've tried and its not what I expected

Time:08-07

items = [4, 6, 2, 2, 6, 4, 4, 4]
result = sorted(items, key = items.count, reverse= True)

This outputs [4, 4, 4, 4, 6, 2, 2, 6]

instead of what I expected: [4, 4, 4, 4, 6, 6, 2, 2]

CodePudding user response:

The problem is that both 2 and 6 have the same frequency in your list, so the order that they get sorted in is arbitrary. If you'd like to sort first by frequency, then by value, you can do that easily by exploiting the fact that a tuple is sorted first by the value in index 0, then the value in index 1, and so on.

To do that, we can create a function that constructs a tuple of the item count and the value, and use that function as the sorting key:

items = [4, 6, 2, 2, 6, 4, 4, 4]
sort_key = lambda x: (items.count(x), x)
result = sorted(items, key = sort_key, reverse = True)

Output:

[4, 4, 4, 4, 6, 6, 2, 2]

CodePudding user response:

Try:

import collections
lst = [4, 6, 2, 2, 6, 4, 4, 4]
from collections import Counter
print([n for n,count in Counter(lst).most_common() for i in range(count)])

>>> [4, 4, 4, 4, 6, 6, 2, 2]

Surprisingly, most methods used to calculate frequency end up with the same problem, but not this one.

  • Related