python - python - 如何按字母的频率对字母进行排序?

我想按字母的频率降序排列字母,

如何按字母顺序排序,然后按字母顺序选择最高频率的n个字母,


string='ddddaacccbb'


n=3


from collections import Counter


counter=Counter(string)



假设单词是ddddaaccbb,n是3,那么它应该打印acd,这个n是字母数量

时间:

使用计数器的most_common()方法。


from collection import Counter


string = 'ddddaacccbb'


n = 3


count = Counter(string)


print([letter for letter, _ in count.most_common(n)])



输出将为

 
['d','c','a']



 

如果要在输出上按字母顺序排序,可以对结果进行排序。


print(sorted(letter for letter, _ in count.most_common(n)))



输出:

 
['a','c','d']



 

你只需通过Counter.most_common检索列表中的第n个元素,并提取字母,最小化的排序是most_common方法,


string='aacccbbdddd'


n=3


from collections import Counter


counter=Counter(string)



#Get the letters of n top values


res = [letter[0] for letter in counter.most_common(n)]


print(res)



输出将为

 
['d','c','a']



 

你可以使用sorted,并且检索计数器的一部分:


keys = sorted(counter, key=lambda x: (counter.get(x), x))


# sort by value, then key


result = keys[-n:]



你可以使用排序函数的key参数:


letters = sorted(counter,key=lambda c:(-counter[c],c))[:3]



# ['d', 'c', 'a'] 




letters = sorted(counter,key=lambda c:(counter[c],c))[-3:]



# ['a', 'c', 'd']



...