How do I sort this list by frequency, this is what I've tried and its not what I expected
Question:
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]
Answers:
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.
You actually have succeeded in sorting the list by frequency. The problem is that both 2 and 6 have the same frequency, so their sort order is left unchanged. 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]
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]
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.
You actually have succeeded in sorting the list by frequency. The problem is that both 2 and 6 have the same frequency, so their sort order is left unchanged. 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]