【问题标题】:How to get all the keys with the same highest value?如何获得具有相同最高值的所有键?
【发布时间】:2014-11-03 22:05:01
【问题描述】:

如果我有一本带有相应频率值的字典:

numbers = {'a': 1, 'b': 4, 'c': 1, 'd': 3, 'e': 3}

要找到最高的,我知道的是:

mode = max(numbers, key=numbers.get)
print mode

然后打印出来:

b

但如果我有:

numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}

并应用上面的'max'函数,输出为:

d

我需要的是:

d,e

或类似的东西,显示两个键。

【问题讨论】:

    标签: python python-2.7 dictionary key


    【解决方案1】:
    numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}
    max_value = max(numbers.values())
    
    
    [k for k,v in numbers.items() if v == max_value]
    

    打印

     ['e', 'd']
    

    它的作用是,通过.items 遍历所有条目,然后检查该值是否为最大值,如果是,则将键添加到列表中。

    【讨论】:

      【解决方案2】:
      numbers = {'a': 1, 'b': 4, 'c': 1, 'd':4 , 'e': 3}
      mx_tuple = max(numbers.items(),key = lambda x:x[1]) #max function will return a (key,value) tuple of the maximum value from the dictionary
      max_list =[i[0] for i in numbers.items() if i[1]==mx_tuple[1]] #my_tuple[1] indicates maximum dictionary items value
      
      print(max_list)
      

      此代码将在 O(n) 中运行。 O(n) 在列表理解中找到最大值和 O(n)。所以总的来说它仍然是O(n)。

      注意:O(2n) 等价于 O(n)。

      【讨论】:

        【解决方案3】:

        collections.Counter 对象对此也很有用。它为您提供了一个 .most_common() 方法,该方法将为您提供所有可用值的键和计数:

        from collections import Counter
        numbers = Counter({'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3})
        values = list(numbers.values())
        max_value = max(values)
        count = values.count(max_value)
        numbers.most_common(n=count)
        

        【讨论】:

          【解决方案4】:

          您可以使用 .items() 属性并在 count, key 的元组之后排序 - 在类似的计数上,键将决定:

          d = ['a','b','c','b','c','d','c','d','e','d','b']
          
          from collections import Counter
          get_data = Counter(d)
          
          # sort by count, then key
          maxmax = sorted(get_data.items(), key=lambda a: (a[1],a[0]) )
          for elem in maxmax:
              if elem[1] == maxmax[0][1]:
                  print (elem)
          

          输出:

          ('a', 1) 
          ('e', 1)   # the last one is the one with "highest" key
          

          要获得“最高”键,请使用maxmax[-1]

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-05-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多