简体   繁体   English

在字典中找到第 n 个最大值的键

[英]find key in dictionary with n-th largest value

given a dictionary like this: example_dict ={"mark":13, "steve":3, "bill":6, "linus":11}给定这样的字典: example_dict ={"mark":13, "steve":3, "bill":6, "linus":11}

finding the key with max value is easy using max(example_dict.items(), key=operator.itemgetter(1)) and min value using min(example_dict.items(), key=operator.itemgetter(1))使用max(example_dict.items(), key=operator.itemgetter(1))和使用min(example_dict.items(), key=operator.itemgetter(1))很容易找到具有最大值的键

What's the easiest way to find the key with the n-th largest value?找到具有第 n 个最大值的键的最简单方法是什么? eg the key with the 2nd largest value here is linus例如这里第二大值的键是linus

Use nlargest :使用nlargest

import heapq

example_dict ={"mark":13, "steve":3, "bill":6, "linus":11}

*_, res = heapq.nlargest(2, example_dict, key=example_dict.get)
print(res)

Output Output

linus

From the documentation:从文档中:

Return a list with the n largest elements from the dataset defined by iterable.从 iterable 定义的数据集中返回一个包含 n 个最大元素的列表。 key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). key(如果提供)指定一个参数的 function,该参数用于从可迭代的每个元素中提取比较键(例如,key=str.lower)。

A note on performance, also from the documentation:关于性能的说明,也来自文档:

perform best for smaller values of n.对于较小的 n 值表现最佳。 For larger values, it is more efficient to use the sorted() function.对于较大的值,使用 sorted() function 更有效。 Also, when n==1, it is more efficient to use the built-in min() and max() functions.此外,当 n==1 时,使用内置的 min() 和 max() 函数效率更高。 If repeated usage of these functions is required, consider turning the iterable into an actual heap.如果需要重复使用这些函数,请考虑将可迭代对象转换为实际堆。

Note that it returns a list, that is why you discard the first n-1 elements请注意,它返回一个列表,这就是您丢弃前n-1元素的原因

Use QuickSelect algorithm.使用快速选择算法。 It works in O(n) on average它平均在 O(n) 中工作

Something like this:像这样的东西:

def nth_largest_key(di, n):
    sorted_items = sorted(di.items(), key=lambda item: item[1],
                          reverse=True)
    return sorted_items[n-1][0]


input_di = {"mark":13, "steve":3, "bill":6, "linus":11}
print(nth_largest_key(input_di, int(input().strip())))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM