Sort list by frequency in python

2019-02-09 04:07发布

问题:

Is there any way (in python), wherein I can sort a list by its frequency?

For example,

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

the above list would be sorted in the order of the frequency of its values to create the following list, where the item with the greatest frequency is placed at the front:

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

回答1:

I think this would be a good job for a collections.Counter:

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

Alternatively, you could write the second line without a lambda:

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

If you have multiple elements with the same frequency and you care that those remain grouped, we can do that by changing our sort key to include not only the counts, but also the value:

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


回答2:

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:

Was practising this one for fun. This solution use less time complexity.

lis = [1,2,3,4,3,3,3,6,7,1,1,9,3,2]
dic = {}
for num in lis:
    if num not in dic:
        dic[num] = 0
    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)


回答4:

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)


回答5:

You can use below methods. It is written in simple python.

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));