Sort list by frequency

后端 未结 7 1149
孤城傲影
孤城傲影 2020-11-27 07:23

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

相关标签:
7条回答
  • 2020-11-27 07:54

    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));
    
    0 讨论(0)
提交回复
热议问题