【问题标题】:How do you find which value occurs the most in a dictionary?您如何找到字典中出现次数最多的值?
【发布时间】:2015-01-30 00:36:07
【问题描述】:

在包含键和值列表的字典中,如何找到值列表中出现频率最高的值?我假设您使用 for 循环并附加到列表,但不确定如何执行此操作。我还想打印最常出现的值?

谢谢!

请记住,我对编程很陌生,不熟悉 lambda 或其他复杂的方法来解决这个问题。

【问题讨论】:

    标签: python dictionary frequency


    【解决方案1】:

    应该按值对字典进行排序:

    d = {'a': 5, 'b': 3, 'c': 5, 'd': 1, 'e': 5}
    
    print(d[sorted(d, key=lambda k: d[k])[-1]])
    

    Cyber​​ 是对的,上面的值最大。请参阅下文以获得最频繁的信息。我的想法是在不使用 collections.Counter 的情况下获得价值。

    counts = {}
    for k in d:
        counts[d[k]] = counts.get(d[k], 0) + 1
    
    
    print(sorted(counts)[-1])   # 5
    print(counts)               # {1: 1, 3: 1, 5: 3}
    

    【讨论】:

      【解决方案2】:

      一种方法是使用collections.Counter

      from collections import Counter
      
      >>> d = {'a': 5, 'b': 3, 'c': 5, 'd': 1, 'e': 5}
      >>> c = Counter(d.values())
      >>> c
      [(5, 3), (1, 1), (3, 1)]
      
      >>> c.most_common()[0]
      (5, 3)   # this is the value, and number of appearances
      

      【讨论】:

      • 不幸的是,这有点太复杂了,我无法理解。
      猜你喜欢
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 2019-10-27
      相关资源
      最近更新 更多