I am trying to sort the list of items below by the frequency of the individual items. With the largest first, to the smallest last. I wanted to see if I can do it first with sorted() before trying with collection.Counter.
Code I have so far is;
items = [4, 6, 2, 2, 6, 4, 4, 4]
x = sorted(items, key=items.count, reverse=True)
print(x)
The above code prints; [4, 4, 4, 4, 6, 2, 2, 6]
Rather than; [4, 4, 4, 4, 6, 6, 2, 2]
Could someone please explain why it doesn't go "6,6,2,2"?
6and2both occur twice, so the sort value for all6and2is "2", meaning they're all equal as far as the sorting algorithm is concerned and their relative order is undefined and/or won't change.x = sorted(sorted(items, reverse=True), key=items.count, reverse=True), i.e. pre-sort to "group" same numbers.