【问题标题】:Python - find sum of list in dictionary & then find the list with the lowest valuePython - 在字典中查找列表的总和,然后找到具有最低值的列表
【发布时间】:2020-08-18 02:37:05
【问题描述】:

我正在为纸牌游戏创建一个简单的记分员。得分最低的人获胜。我将球员和分数保存在字典中:

players = {'bob': [3,6,4,3,7,3,6], 'joe': [3,7,5,9,9,7,8]}

我可以通过以下方式总结每个玩家的分数:

for player, score in players.items():
        print(f"\n{player.title()}'s final score is {sum(score)}")

现在我想宣布获胜者(得分最低的人),但我无法让它发挥作用。这是我尝试过的:

for points in players.values():
    score = sum(points)
winner = min(score)
print(f"The winner is {winner}!")

感谢您的帮助!

【问题讨论】:

  • 我认为这里已经有了很好的答案,所以我只想指出你的错误。当你说score = sum(points) 时,你用一个新值重写你的score,所以你的最后一个将是字典中的最后一个值。相反,您应该说score+=sum(points)。另外,请确保您的score 在for 循环之前定义。

标签: python


【解决方案1】:

试试这个

winner=min(players, key=lambda p:sum(players[p]))

【讨论】:

  • 谢谢@kuldipchaudhari 我还在学习理解,不理解这部分代码:p:sum(players[p])。你有几分钟的时间解释一下,让我明白一切吗?
【解决方案2】:
print('The winner is {}'.format(min(players, key=lambda k: sum(players[k]))))

【讨论】:

    【解决方案3】:

    首先声明一个高数和一个空的获胜者变量

    创建一个打印所有dictionary 值名称和点的for 语句

    point = 1000000; winner = ''
    
    for name,points in players.items():
        temp = sum(points) #sum of all the num in the list
        if point > temp: # if point is > than the sum of the list replace the value of points
            point = temp
            winner = name
    
    print(f"The winner is {winner}!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多