Sort list by frequency

Is there a way in Python where I can sort the list by frequency?

For instance,

[1,2,3,4,3,3,3,6,7,1,1,9,3,2]

The list above will be sorted in the order of frequency of its values ​​to create the following list, in which the element with the highest frequency is located in front:

[3,3,3,3,3,1,1,1,2,2,4,6,7,9]
+13
source share
7 answers

I think that would be a good job for collections.Counter.

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])

Alternatively, you can write a second line without a lambda:

counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)

If you have several elements with the same frequency, and you make sure that they remain grouped, we can do this by changing our sort key, including not only a number, but also a value:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: (counts[x], x), reverse=True)
+27
l = [1,2,3,4,3,3,3,6,7,1,1,9,3,2]
print sorted(l,key=l.count,reverse=True)

[3, 3, 3, 3, 3, 1, 1, 1, 2, 2, 4, 6, 7, 9]
+3

. .

from collections import defaultdict

lis = [1,2,3,4,3,3,3,6,7,1,1,9,3,2]

dic = defaultdict(int)
for num in lis:
    dic[num] += 1

s_list = sorted(dic, key=dic.__getitem__, reverse=True)

new_list = []
for num in s_list:
    for rep in range(dic[num]):
        new_list.append(num)

print(new_list)
+1

Counter , most_common , ,

>>> lst = [1,2,3,4,3,3,3,6,7,1,1,9,3,2]
>>> 
>>> from collections import Counter
>>> [n for n,count in Counter(lst).most_common() for i in range(count)]
[3, 3, 3, 3, 3, 1, 1, 1, 2, 2, 4, 6, 7, 9]
0

.

: , .

import collections 

def frequency_sort(a):
    f = collections.Counter(a)
    a.sort(key = lambda x:(-f[x], x))
    return a
0
from collections import Counter
a = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
count = Counter(a)
a = []
while len(count) > 0:
    c = count.most_common(1)
    for i in range(c[0][1]):
        a.append(c[0][0])
    del count[c[0][0]]
print(a)
-3

. .

def frequencyIdentification(numArray):
frequency = dict({});
for i in numArray:
    if i in frequency.keys():
            frequency[i]=frequency[i]+1;
    else:
            frequency[i]=1;         
return frequency;

def sortArrayBasedOnFrequency(numArray):
    sortedNumArray = []
    frequency = frequencyIdentification(numArray);
    frequencyOrder = sorted(frequency, key=frequency.get);
    loop = 0;
    while len(frequencyOrder) > 0:
        num = frequencyOrder.pop()
        count = frequency[num];
        loop = loop+1;
        while count>0:
            loop = loop+1;
            sortedNumArray.append(num);
            count=count-1;
    print("loop count");
    print(loop);
    return sortedNumArray;  

a=[1, 2, 3, 4, 3, 3, 3, 6, 7, 1, 1, 9, 3, 2]
print(a);
print("sorted array based on frequency of the number"); 
print(sortArrayBasedOnFrequency(a));
-3
source

All Articles