我有一本字典,上面写着{key: count}
我正在尝试为heapq.nlargest()编写一个键函数,它基于计数进行排序,如果有关系,我必须根据键的字母顺序(a-z)进行排序。我必须使用heapq.nlargest,因为N很大,k=10很小。
这就是我现在所拥有的,status_count = {'MANAGEMENT ANALYSTS': 13859, 'COMPUTER PROGRAMMERS': 72112}
但是,如果打破了按字母顺序排列的关系,这是不正确的。请帮忙!
最佳答案
最简单的方法是切换到heapq.nsmallest
并重新定义排序键:
from heapq import nsmallest
def sort_key(x):
return -x[1], x[0]
top_k_results = nsmallest(args.top_k, status_count.items(), key=sort_key)
或者,您可以使用
ord
并将负数作为升序:from heapq import nlargest
def sort_key(x):
return x[1], [-ord(i) for i in x[0]]
top_k_results = nlargest(args.top_k, status_count.items(), key=sort_key)
如果需要规范化字符串的大小写,请记住使用
str.casefold
。