【问题标题】:How do I print multiple dictionary keys which have the same value using the max() function如何使用 max() 函数打印具有相同值的多个字典键
【发布时间】:2015-12-06 08:05:49
【问题描述】:

假设我有一个字典,其中包含不同键的多个最大值。我尝试使用代码:

    taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1}
    print(max(taste, key=taste.get))

但它只给我贻贝或帽贝,取决于哪个先来。我尝试设置最高值,然后遍历我的键和每个键,我的值,例如:

    highest = max(taste.values())
    for i in taste.keys():
      for j in taste[i]:
        if j == highest:
          print(i)

但这似乎不起作用,因为您不能像我的字典中的值那样通过整数进行交互。那么最干净,最简单的方法是什么

【问题讨论】:

  • 您到底想要什么作为输出[["Mussels"], [Limpets]] 或任意(随机)顺序中的任何一个?
  • 你只想要if taste[i] == highest,确定吗?

标签: python python-3.x dictionary printing max


【解决方案1】:

这就是我会做的:

highest_value = max(taste.itervalues())
print [key for key, value in taste.iteritems() if value == highest_value]

【讨论】:

    【解决方案2】:

    您可以使用列表推导。

    >>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1}
    >>> highest = max(taste.values())
    >>> [k for k, v in taste.items() if v == highest]
    ['Limpets', 'Mussels']
    

    >>> for i in taste.keys():
    ...     if taste[i] == highest:
    ...         print(i)
    ... 
    Limpets
    Mussels
    

    【讨论】:

      【解决方案3】:

      由于您有多个值是集合的最大值,因此您需要有点聪明地过滤掉具有相同值的所有键。

      这更像是一种排序操作,而不是最大操作。

      >>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1}
      >>> ordered_by_rating = sorted(list(taste.items()), key=lambda x: x[1], reverse=True)
      >>> top_rating = max(ordered_by_rating, key=lambda x: x[1])[1]
      >>> only_top = [x[0] for x in filter(lambda x: x[1] == top_rating, ordered_by_rating)]
      >>> only_top
      ['Mussels', 'Limpets']
      

      您可以通过减少必须经过的循环次数来压缩上述内容:

      >>> [k for k,v in taste.items() if v == max(taste.values())]
      ['Mussels', 'Limpets']
      

      【讨论】:

        【解决方案4】:

        此解决方案使用 Python3:

        maxkeys = [k for k, v in taste.items() if v == max(taste.values())]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-11
          • 2021-08-17
          • 1970-01-01
          相关资源
          最近更新 更多