【问题标题】:summing nested dictionary values in python在python中对嵌套字典值求和
【发布时间】:2017-02-23 16:02:11
【问题描述】:

我们在一个二级字典中表示一系列比赛中的击球手得分,如下所示:

{'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}

每场比赛都由一个字符串标识,每个玩家也是如此。分数都是整数。与比赛相关的名字不固定(这里他们是match1,match2,match3),球员的名字也不是固定的。球员不需要在所有比赛中记录得分

定义一个 Python 函数 orangecap(d) 读取这种形式的字典 d 并识别总分最高的玩家。你的函数应该返回一对(playername,topscore),其中playername是一个字符串,得分最高的玩家的名字,topscore是一个整数,playername的总得分。

【问题讨论】:

  • 虽然可以在这里寻求家庭作业的帮助,但希望您首先尝试解决问题,展示您编写的代码,并描述它如何无法按预期工作。跨度>
  • def orangecap(d): d = dict((key, sum(vals)) for key, vals in d.items()) print(d)
  • 请点击您的问题下方的"edit" 链接,并添加代码和说明。

标签: python dictionary


【解决方案1】:

总结数据并选择最高值通常可以使用collections.Counter() 完成,如下所示:

def orangecap(d):
    from collections import Counter
    return sum((Counter(game) for game in d.values()), Counter()).most_common(1)[0]

【讨论】:

    【解决方案2】:

    不如 Rob 的答案漂亮,但不需要任何导入:

    def orangecap(d):
        first_run = 1
        for match in d:
            for player in d[match]:
                if first_run == 1:
                    first_run = 0
                    topscore = d[match][player]
                    playername = d[match]
                elif d[match][player] > topscore:
                    topscore = d[match][player]
                    playername = player
    
        return [playername, topscore]
    

    【讨论】:

      【解决方案3】:

      这是一个故意(!)冗长且不是特别优雅的解决方案,它仅使用相当基本的数据结构,try/except,用于循环和条件。对于初学者来说,我认为这可能更有助于遵循所有步骤的逻辑,即发生的方式和原因。我使用了描述性的变量名称以使其易于理解。如果两个或多个玩家的总分相同,以下代码也将起作用:

      game = {'match1': {'player1': 57, 'player2': 38},
              'match2': {'player3': 9, 'player1': 42},
              'match3': {'player2': 41, 'player4': 63, 'player3': 91},
              'match4': {'player1': 1}}
      
      
      def orangecap(matches):
          players_and_scores = {}
          top_players_and_scores = []
      
          for match in matches:
              for player, score in matches[match].items():
                  try:  # if key already exists
                      players_and_scores[player] += score
                  except:  # if key does not exist yet
                      players_and_scores[player] = score
      
          # all players and their total stores:
          # print(players_and_scores)
      
          for player, score in players_and_scores.items():
              if score == max(players_and_scores.values()):
                  top_players_and_scores.append((player, score))
      
          # return all top players (can be more than one)
          # and their total scores:
          return top_players_and_scores
      
      print(orangecap(game))
      

      输出:

      [('player3', 100), ('player1', 100)]
      

      请注意,我在字典中添加了键 match4 是为了让两个玩家的总分相同。

      Robᵩ 的解决方案更加简洁和优雅,如果您可以遵循它的功能并允许使用collections.Counter(),我们会推荐它。不过,它只会返回得分最高的玩家之一,因此可能需要进行一些调整。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-28
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 2013-08-09
        • 1970-01-01
        相关资源
        最近更新 更多