python字典求最小值,Python:从一个字典获取最小值的键,但具有多个最小值 |
您所在的位置:网站首页 › python字典中值最大的键 › python字典求最小值,Python:从一个字典获取最小值的键,但具有多个最小值 |
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… :) |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |