Reputation: 87
I have a list of elements:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
And need to sort it by the frequency of elements to get this:
[3, 3, 3, 2, 2, 2, 1, 1, 1]
If several elements have the same frequency, sort them by descending value. Can you find any way to do this. I'm using mentioned method but getting my output as:
[1, 1, 1, 2, 2, 2, 3, 3, 3]
My code:
from collections import Counter
list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
c = Counter(list)
x = sorted(c.most_common(), key=lambda x: (-x[1], x[0]))
y = [([v] * n) for (v, n) in x]
z = sum(y, [])
print(z)
Upvotes: 0
Views: 64
Reputation: 2991
L = [1, 2, 3, 1, 2, 3, 1, 2, 3]
sorted_list_1 = sorted(L, lambda x: (L.count(x), -x))
c = Counter(L)
sorted_list_2 = sorted(L, lambda x: (c[x], -x))
Upvotes: 1