在OrderedDict中找到最小值的键 [英] Finding key with minimum value in OrderedDict
本文介绍了在OrderedDict中找到最小值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到其值是排序字典中最低的键,但只能在my_list中的位置为True时。
I need to find the key whose value is the lowest in the ordered dictionary but only when it is True for the position in my_list.
from collections import OrderedDict
my_list = [True,False,False,True,True,False,False,False,]
my_lookup = OrderedDict([('a', 2), ('b', 9), ('c', 4), ('d', 7),
('e', 3), ('f', 0), ('g', -5), ('h', 9)])
我知道如何使用for循环,如
I know how to do it with a for loop like
mins=[]
i=0
for item in my_lookup.items():
if my_list[i]:
mins.append(item)
i+=1
print min(mins,key=lambda x:x[1])[0]
打印
a
因为a在my_list中也是最低的。
because a is lowest that is also True in my_list.
这个工作很长,我想知道如何用理解或一行来做?
This works but it is long and I want to know how to do it with comprehensions or one line?
解决方案
您可以使用 itertools.compress
,键值为 min
正在获取
方法,
You can use itertools.compress
with key to min
being get
method,
>>> from itertools import compress
>>> min(compress(my_lookup, my_list), key=my_lookup.get)
a
这篇关于在OrderedDict中找到最小值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文