Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how to sort list by frequency of elements

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]
like image 957
mnowotka Avatar asked Dec 04 '22 05:12

mnowotka


1 Answers

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]
like image 86
Darth Kotik Avatar answered Dec 08 '22 06:12

Darth Kotik