我想添加单个玩家的分数,并希望显示玩家得分最多的分数。这是我所指的字典的例子:
{'match1': {'player1': 57, 'player2': 38},
'match2': {'player3': 9, 'player1': 42},
'match3': {'player2': 41, 'player4': 63, 'player3': 91}}
我尝试了很多解决方案,但无法制作逻辑,因此它会添加不同比赛中各个球员的得分。任何帮助都会很明显。提前谢谢。
答案 0 :(得分:1)
迭代嵌套的dictionary
并将分数加到玩家总数字典中。
def find_totals(d):
total = {}
for match, results in d.items():
for player, score in results.items():
total[player] = total.get(player, 0) + score
return total
示例输出
>>> d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}}
>>> print find_totals(d)
{'player2': 79, 'player3': 100, 'player1': 99, 'player4': 63}
答案 1 :(得分:0)
def score(match):
players = {}
for key in match:
for player in match[key]:
if player not in players:
players[player] =match[key][player]
else:
players[player]+=match[key][player]
return players
快速浏览,如果播放器不在新词典中,则创建成员资格并将关键点指向该播放器的得分。否则将分数添加到该玩家的总数