Reputation: 87
I have a list of numbers list: [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]. I want to sort it by the frequency of elements to get this: [1, 1, 1, 1, 3, 3, 3, 2, 2, 2].
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, 1, 2, 2, 2, 3, 3, 3].
from collections import Counter
list = [1, 2, 3, 1, 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: 1
Views: 338
Reputation: 46849
if your list is long, you may want to have to sort only the items that occur the same amount of times:
from collections import Counter
from itertools import groupby
lst = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(lst)
ret = []
for key, group in groupby(c.most_common(), key=lambda x: x[1]):
items = sorted((item for item, _ in group), reverse=True)
for item in items:
ret.extend(key * [item])
print(ret)
# [1, 1, 1, 1, 3, 3, 3, 2, 2, 2]
Upvotes: 1
Reputation: 82765
Looks like you need to use reverse=True
Ex:
from collections import Counter
data = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(data)
data.sort(key=lambda x: (c[x], x), reverse=True)
print(data)
Output:
[1, 1, 1, 1, 3, 3, 3, 2, 2, 2]
Upvotes: 3