【问题标题】:key function for heapq.nlargest()heapq.nlargest() 的关键函数
【发布时间】:2018-10-30 10:23:38
【问题描述】:

我有一本带有{key: count} 的字典,比如说 status_count = {'MANAGEMENT ANALYSTS': 13859, 'COMPUTER PROGRAMMERS': 72112} 我正在尝试为 heapq.nlargest() 编写一个基于计数排序的键函数,如果有关系,我必须根据键的字母顺序(a-z)进行排序。我必须使用 heapq.nlargest 因为非常大的 N 和小的 k = 10。

这是我到现在得到的,

top_k_results = heapq.nlargest(args.top_k, status_count.items(), key=lambda item: (item[1], item[0])) 但是,如果按字母顺序打破联系,这将是不正确的。请帮忙!

【问题讨论】:

  • 你能展示你正在编写的字典的样本吗?
  • @Austin 我刚刚更新了问题的详细信息。

标签: python python-3.x lambda heap python-collections


【解决方案1】:

最简单的可能是切换到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

【讨论】:

  • 感谢您的回答。我有长度 > 1 的字符串,ord() 我猜只接受长度为 1 的字符串。有没有办法克服这个问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 2014-05-27
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多