python 在具有非零值的字典中找到最大键的有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1555968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:34:26  来源:igfitidea点击:

Efficient way to find the largest key in a dictionary with non-zero value

pythondictionary

提问by clark

I'm new Python and trying to implement code in a more Pythonic and efficient fashion. Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?

我是 Python 新手,正在尝试以更 Pythonic 和高效的方式实现代码。给定一个带有数字键和值的字典,找到具有非零值的最大键的最佳方法是什么?

Thanks

谢谢

回答by Nicholas Riley

Something like this should be reasonably fast:

这样的事情应该相当快:

>>> x = {0: 5, 1: 7, 2: 0}
>>> max(k for k, v in x.iteritems() if v != 0)
1

(removing the != 0will be slightly faster still, but obscures the meaning somewhat.)

(删除!= 0will 仍然稍微快一点,但有点模糊了含义。)

回答by Corey Goldberg

To get the largest key, you can use the maxfunction and inspect the keys like this:

要获得最大的键,您可以使用该max函数并像这样检查键:

max(x.iterkeys())

To filter out ones where the value is 0, you can use a generator expression:

要过滤掉值为 0 的值,您可以使用生成器表达式

(k for k, v in x.iteritems() if v != 0)

You can combine these to get what you are looking for (since maxtakes only one argument, the parentheses around the generator expression can be dropped):

你可以组合这些来得到你想要的东西(因为max只需要一个参数,可以去掉生成器表达式周围的括号):

max(k for k, v in x.iteritems() if v != 0)

回答by u0b34a0f6ae

Python's max function takes a key=parameter for a "measure" function.

Python 的 max 函数接受key=一个“测量”函数的参数。

data = {1: 25, 0: 75}
def keymeasure(key):
    return data[key] and key

print max(data, key=keymeasure)

Using an inline lambda to the same effect and same binding of local variables:

使用内联 lambda 达到相同的效果和相同的局部变量绑定:

print max(data, key=(lambda k: data[k] and k))

last alternative to bind in the local var into the anonymous key function

将本地变量绑定到匿名键函数的最后一种选择

print max(data, key=(lambda k, mapping=data: mapping[k] and k))

回答by Gubatron

If I were you and speed was a big concern, I'd probably create a new container class "DictMax" that'd keep track of it's largest non-zero value elements by having an internal stack of indexes, where the top element of the stack is always the key of the largest element in the dictionary. That way you'd get the largest element in constant time everytime.

如果我是你并且速度是一个大问题,我可能会创建一个新的容器类“DictMax”,通过内部索引堆栈来跟踪它最大的非零值元素,其中顶部元素stack 始终是字典中最大元素的键。这样你每次都会在恒定时间内获得最大的元素。