Python:从一个字典获取最小值的键,但具有多个最小值 [英] Python: get key with the least value from a dictionary BUT multiple minimum values
问题描述
我正在尝试一样做
Python:从字典获取最小值的密钥,我们要在字典中获取与最小值对应的键。
最好的方法似乎是:
min(d, key = d.get)
但是,我想应用于具有多个最小值的字典:
d = {'a':1,'b':2,'c' }
请注意,上述答案将是:
>>> min(d,key = d.get)
'a'
然而,我需要两个两个具有最小值的键,即 a
和 c
。 p>
最好的方法是什么?
(最终我想随机选择两者之一,但是
一个简单的选项是先确定最小值,然后选择所有键映射到该最小值:
min_value = min(d.itervalues())
min_keys = [k for k in d如果d [k] == min_value]
对于Python 3,使用 d .values()
而不是 d.itervalues()
。
这需要两个通过字典,但应该是这样做的最快的选择之一。
使用油藏采样,可以实现一个si ngle pass方法随机选择一个项目:
it = d.iteritems()
min_key,min_value = next(it)
num_mins = 1
for k,v in it:
if v< min_value:
num_mins = 1
min_key,min_value = k,v
elif v == min_value:
num_mins + = 1
if random.randrange(num_mins)= = 0:
min_key = k
写下这段代码后,我认为这个选项是相当理论上的兴趣...:)
I'm trying to do the same as Python: get key with the least value from a dictionary, where we want to get the key corresponding to the minimum value in a dictionary.
The best way appears to be:
min(d, key=d.get)
BUT I want to apply this on a dictionary with multiple minimum values:
d = {'a' : 1, 'b' : 2, 'c' : 1}
Note that the answer from the above would be:
>>> min(d, key=d.get)
'a'
However, I need both the two keys that have a minimum value, namely a
and c
.
What would be the best approach?
(Ultimately I want to pick one of the two at random, but I don't think this is relevant).
One simple option is to first determine the minimum value, and then select all keys mapping to that minimum:
min_value = min(d.itervalues())
min_keys = [k for k in d if d[k] == min_value]
For Python 3 use d.values()
instead of d.itervalues()
.
This needs two passes through the dictionary, but should be one of the fastest options to do this anyway.
Using reservoir sampling, you can implement a single pass approach that selects one of the items at random:
it = d.iteritems()
min_key, min_value = next(it)
num_mins = 1
for k, v in it:
if v < min_value:
num_mins = 1
min_key, min_value = k, v
elif v == min_value:
num_mins += 1
if random.randrange(num_mins) == 0:
min_key = k
After writing down this code, I think this option is of rather theoretical interest… :)
这篇关于Python:从一个字典获取最小值的键,但具有多个最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!