python中嵌套字典值的求和
我们在两级词典中表示一系列比赛中击球手的得分,如下所示:python中嵌套字典值的求和,python,dictionary,Python,Dictionary,我们在两级词典中表示一系列比赛中击球手的得分,如下所示: {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91} 每场比赛都由一个字符串标识,每个球员也是如此。分数都是整数。与比赛相关的名字在这里不是固定的,它们是match1、match2、match3,也不是球员的名字。球员不需要在所有比赛
{'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}
每场比赛都由一个字符串标识,每个球员也是如此。分数都是整数。与比赛相关的名字在这里不是固定的,它们是match1、match2、match3,也不是球员的名字。球员不需要在所有比赛中都记录分数
定义一个Python函数orangecapd,该函数读取这种形式的字典d,并识别总分最高的玩家。您的函数应该返回一对playername,topscore,其中playername是字符串,是得分最高的玩家的名称,topscore是整数,是playername的总分。汇总数据并选择最高值通常可以通过集合来完成。计数器如下:
def orangecap(d):
from collections import Counter
return sum((Counter(game) for game in d.values()), Counter()).most_common(1)[0]
不如Rob的答案漂亮,但不需要任何导入:
def orangecap(d):
first_run = 1
for match in d:
for player in d[match]:
if first_run == 1:
first_run = 0
topscore = d[match][player]
playername = d[match]
elif d[match][player] > topscore:
topscore = d[match][player]
playername = player
return [playername, topscore]
这里是一个有目的的!冗长而不是特别优雅的解决方案,它只使用相当基本的数据结构,try/except,用于循环和条件。对于初学者来说,我想这可能更有助于遵循所有步骤的逻辑,即如何和为什么进行。我使用描述性变量名使其易于理解。如果两名或两名以上球员的总分相同,则以下代码也适用:
game = {'match1': {'player1': 57, 'player2': 38},
'match2': {'player3': 9, 'player1': 42},
'match3': {'player2': 41, 'player4': 63, 'player3': 91},
'match4': {'player1': 1}}
def orangecap(matches):
players_and_scores = {}
top_players_and_scores = []
for match in matches:
for player, score in matches[match].items():
try: # if key already exists
players_and_scores[player] += score
except: # if key does not exist yet
players_and_scores[player] = score
# all players and their total stores:
# print(players_and_scores)
for player, score in players_and_scores.items():
if score == max(players_and_scores.values()):
top_players_and_scores.append((player, score))
# return all top players (can be more than one)
# and their total scores:
return top_players_and_scores
print(orangecap(game))
输出:
[('player3', 100), ('player1', 100)]
注意,我在字典中添加了关键匹配4,以便让两个玩家的总分相同
抢劫ᵩ's的解决方案更加简洁和优雅,如果您能够遵循它的功能并允许使用collections.Counter,则建议您使用它。不过,它将只返回一个得分最高的玩家,因此可能需要进行一些调整。虽然可以在这里寻求家庭作业方面的帮助,但希望您首先尝试解决问题,展示您编写的代码,并描述它如何不按您的预期工作。def orangecapd:d=dictkey,Summals for key,d.items Printd中的VAL请单击问题下的链接,并在此处添加代码和说明。