問題描述
對(duì)于學(xué)校,我正在編寫一個(gè)小程序來為游戲排名列表.我為此使用字典,將播放器的名稱作為鍵名,將分?jǐn)?shù)作為鍵值.將有 10 場(chǎng)比賽,每場(chǎng)比賽都有一個(gè)自動(dòng)排名系統(tǒng),我將其打印到文件中.我已經(jīng)設(shè)法編寫了排名系統(tǒng),但現(xiàn)在我面臨著一個(gè)更大的挑戰(zhàn),我無法解決:
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:
我必須做一個(gè)整體排名,這意味著某個(gè)玩家名字可以在多個(gè)比賽中獲得多個(gè)分?jǐn)?shù),但我只需要保留副本的最高分?jǐn)?shù).
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.
簡(jiǎn)而言之:我需要一些幫助來保持重復(fù)鍵的最高值:
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}
正常的合并選項(xiàng)只采用第二個(gè)字典,因此采用該值.
the normal merge option just takes the second dict and thus that value.
請(qǐng)?zhí)崆?/p>
推薦答案
你需要有一個(gè)函數(shù)來記錄每個(gè)玩家的最高分?jǐn)?shù).如果還沒有玩家,它會(huì)將玩家添加到總數(shù)中,否則如果它更高,則添加它.像這樣的:
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]
這篇關(guān)于保持字典中重復(fù)鍵的最高值的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!