假设我有一本字典:
{key1:value1........... keyn:valuen}
假设我想写一个函数
def return_top_k(dictionary, k):
return list_of_keys_sorted
什么是最有效的方法(就大 O 而言)来获取具有前 k 个值的键(保持顺序,即最高值的键出现在开头......等等。)
最佳答案
O(n log k)
:
import heapq
k_keys_sorted = heapq.nlargest(k, dictionary)
您可以使用 key
关键字参数来指定应该用作排序键的内容,例如:
k_keys_sorted_by_values = heapq.nlargest(k, dictionary, key=dictionary.get)
关于python - 在字典python中找到前k个最大的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266617/