给出一个字典和这样的变量:
dic = {0 : 'some', 10 : 'values', 20 : 'whatever'}
var = 14
Run Code Online (Sandbox Code Playgroud)
我想从字典中获取密钥值最大但低于或等于变量的值.我不知道这是否清楚,但在这种情况下我正在寻找10.
我想出了这个函数,但我想知道是否有更简单的方法来做它,因为我对python很新.
def get_greatest_key(dic, var):
# if the key exists no need to search
if var in dic:
return dic[var]
else:
# create a list with all the keys sorted in reverse
l = sorted(dic, key=dic.get)
i = 0
while i < len(l):
# parse the list
if l[i] <= var:
return dic[l[i]]
i += 1
# by default we return the last element in the dictionary
return dic[l[len(l) - 1]]
Run Code Online (Sandbox Code Playgroud)
如果希望最大键小于或等于var,则可以将生成器表达式传递给max函数:
>>> dic = {0 : 'some', 10 : 'values', 20 : 'whatever'}
>>> var = 14
>>> max(k for k in dic if k <= var)
10
Run Code Online (Sandbox Code Playgroud)
具有相应的价值
>>> dic[max(k for k in dic if k <= var)]
'values'
Run Code Online (Sandbox Code Playgroud)
ValueError如果max你认为合适的参数为空,你可以决定如何处理抛出.
| 归档时间: |
|
| 查看次数: |
2128 次 |
| 最近记录: |