保持字典中重复键的最高值

时间:2023-01-06
本文介绍了保持字典中重复键的最高值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

对于学校,我正在编写一个小程序来为游戏排名列表.我为此使用字典,将播放器的名称作为键名,将分数作为键值.将有 10 场比赛,每场比赛都有一个自动排名系统,我将其打印到文件中.我已经设法编写了排名系统,但现在我面临着一个更大的挑战,我无法解决:

For school i am writing a small program for a rankinglist for a game. I am using dicts for this, with the name of the player as keyname, and the score as keyvalue. there will be 10 games, and each game will have an automatic ranking system which i print to file. ive already managed to code the ranking system, but now im facing a bigger challange which i cannot solve:

我必须做一个整体排名,这意味着某个玩家名字可以在多个比赛中获得多个分数,但我只需要保留副本的最高分数.

I have to make an overall ranking, which means someplayername can be in several contests with several scores, but i need to only keep the highest score of a duplicate.

简而言之:我需要一些帮助来保持重复键的最高值:

In short: I need some help with keeping the duplicate key with the highest value:

像这样:

dict1 = {"a": 6, "b": 4, "c": 2, "g": 1}
dict2 = {"a": 3, "f": 4, "g": 5, "d": 2}
dictcombined = {'a': 6, 'b': 4, 'c': 2, 'g': 5, 'f': 4, 'd': 2}

正常的合并选项只采用第二个字典,因此采用该值.

the normal merge option just takes the second dict and thus that value.

请提前

推荐答案

你需要有一个函数来记录每个玩家的最高分数.如果还没有玩家,它会将玩家添加到总数中,否则如果它更高,则添加它.像这样的:

You need to have a function that will keep track of the highest scores for each player. It will add a player to the total if not already there, otherwise adding it if it's higher. Something like this:

def addScores(scores, total):
    for player in scores:
        if player not in total or total[player] < scores[player]:
            total[player] = scores[player]

这篇关于保持字典中重复键的最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Pandas - 有条件的删除重复项 下一篇:通过 hashlib 查找重复文件?

相关文章

最新文章