高效的方式找到非零值字典中最大的键 [英] Efficient way to find the largest key in a dictionary with non-zero value

查看:153
本文介绍了高效的方式找到非零值字典中最大的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的Python,试图以更加诡异和高效的方式实现代码。
给出一个带有数字键和值的字典,找到最大的非零值的最佳方法是什么?

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?

谢谢

推荐答案

这样的事情应该是相当快的:

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

(删除!= 0 将稍微更快一点,但有些含糊)。

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

这篇关于高效的方式找到非零值字典中最大的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆