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]
这篇关于保持字典中重复键的最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:保持字典中重复键的最高值
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
