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]
这篇关于保持字典中重复键的最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:保持字典中重复键的最高值


基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01