在python中按频率排序列表

时间:2014-09-12 19:22:06

标签: python list indexing frequency

有没有办法(在python中),我可以按频率对列表进行排序?

例如,

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

上面的列表将按其值的频率顺序排序,以创建以下列表,其中频率最高的项目位于前面:

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

7 个答案:

答案 0 :(得分:24)

我认为这对collections.Counter

来说是个不错的选择
counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])

或者,您可以编写没有lambda的第二行:

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

如果您有多个具有相同频率的元素,您可以关注那些仍然分组的元素,我们可以通过更改排序键来不仅包括计数,还包括

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

答案 1 :(得分:3)

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]

答案 2 :(得分:1)

正在练习这个有趣。此解决方案使用的时间复杂度更低。

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)

答案 3 :(得分:0)

您可以使用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]

答案 4 :(得分:0)

如果要使用双比较器。

例如:按频率降序对列表进行排序,如果发生冲突,则较小的列表排在第一位。

import collections 

def frequency_sort(a):
    f = collections.Counter(a)
    a.sort(key = lambda x:(-f[x], x))
    return a

答案 5 :(得分:-3)

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)

答案 6 :(得分:-3)

您可以使用以下方法。它是用简单的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));