I have a list of elements: [ 3, 3, 6, 6, 6, 5, 5, 8 ]
and need to sort it by the frequency of elements to get this: [ 6, 6, 6, 3, 3, 5, 5, 8 ]
of several elements have the same frequency sort them by value. Can you find any shorter way than this?
import collections
from operator import itemgetter, attrgetter
def freq_sort(arr):
counter=collections.Counter(arr)
com = sorted(counter.most_common(), key=itemgetter(1,0), reverse=True)
com = map(lambda x: [x[0]] * x[1], com)
return [item for sublist in com for item in sublist]
Try this
>>> old_list = [ 3, 3, 6, 6, 6, 5, 5, 8 ]
new_list = sorted(old_list, key = old_list.count, reverse=True)
>>> new_list
[6, 6, 6, 3, 3, 5, 5, 8]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With