Sort list by frequency

懵懂的女人 提交于 2019-11-26 20:56:54

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

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

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)

You can use a Counter to get the count of each item, use its most_common method to get it in sorted order, then use a list comprehension to expand again

>>> 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]
Anonymous
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)

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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!