Python 按频率排序列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25815377/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort list by frequency
提问by user2592835
Is there any way in Python, wherein I can sort a list by its frequency?
在 Python 中有什么方法可以按频率对列表进行排序吗?
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]
采纳答案by mgilson
I think this would be a good job for a collections.Counter:
我认为这对以下人员来说是一份好工作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:
或者,您可以在没有 lambda 的情况下编写第二行:
counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)
If you have multiple elements with the same frequency andyou 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)
回答by Padraic Cunningham
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]
回答by 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)
回答by AVVD
You can use below methods. It is written in simple python.
您可以使用以下方法。它是用简单的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));
回答by gautamaggarwal
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)
回答by Sunitha
You can use a Counterto get the count of each item, use its most_commonmethod to get it in sorted order, then use a list comprehension to expand again
可以使用 aCounter来获取每一项的计数,使用它的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]
回答by Ankit Sharma
In case you want to use a double comparator.
如果您想使用双比较器。
For example: Sort the list by frequency in descending order and in case of a clash the smaller one comes first.
例如:按频率降序对列表进行排序,如果发生冲突,较小的排在最前面。
import collections 
def frequency_sort(a):
    f = collections.Counter(a)
    a.sort(key = lambda x:(-f[x], x))
    return a

