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

keep highest value of duplicate keys in dicts(保持字典中重复键的最高值)
本文介绍了保持字典中重复键的最高值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于学校,我正在编写一个小程序来为游戏排名列表.我为此使用字典,将播放器的名称作为键名,将分数作为键值.将有 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]

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

【网站声明】本站部分内容来源于互联网,旨在帮助大家更快的解决问题,如果有图片或者内容侵犯了您的权益,请联系我们删除处理,感谢您的支持!

相关文档推荐

How to draw a rectangle around a region of interest in python(如何在python中的感兴趣区域周围绘制一个矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 检测和跟踪人员?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在图像的多个矩形边界框中应用阈值?)
How can I download a specific part of Coco Dataset?(如何下载 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根据文本方向检测图像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 检测图像中矩形的中心和角度)