热线电话:13121318867

登录
2019-01-26 阅读量: 695
如何在嵌套字典中以最大总和返回密钥?

假设我有一个字符串,键是字符串,这些键的值是另一个字典,其返回的键是具有int值的字符串。

像这样: results = {'T1':{'team1': 1, 'team2': 3, 'team3': 10}, 'T2': {'team1': 3, 'team2': 1, 'team3': 5}}

我希望我的代码能够返回总体目标最多的团队,如果有一个平局,那么它应该是一个有平局的团队列表。如果它不是平局,我希望有一个长度为1的列表,获胜团队是列表中唯一的字符串。

我想要的路线是为每个团队制作单独的变量,并在这些变量中,将每个锦标赛的目标相加(T1,T2)。然后,使用max函数,我将找到具有最高值的变量,并返回相关获胜团队或相关联的团队的列表。

import operator

results = {'T1':{'team1': 1, 'team2': 3, 'team3': 10}, 'T2': {'team1': 3, 'team2': 1, 'team3': 5}}

def winning_team(results: dict[str, dict[str, int]]) -> list[str]:

team_totals = {}

for tournament in results:

for team in tournament:

team_total = 0

for goals in team:

team_total += goals

team_totals[team] = team_total

winning_list = []

winning_list.append(max(team_totals.iteritems(), key=operator.itemgetter(1))[0])

return winning_list

# when there's no tie

results = {'T1':{'team1': 1, 'team2': 3, 'team3': 10}, 'T2': {'team1': 3, 'team2': 1, 'team3': 5}}

>>> winning_team(results)

['team3']

# when there's a tie

new_results = {'T1':{'team1': 10, 'team2': 3, 'team3': 10}, 'T2': {'team1': 5, 'team2': 1, 'team3': 5}}

>>> winning_team(new_results)

['team1', 'team3'] # doesn't need to be in any particular order!

解决办法:

检查关系并将其作为列表返回。

import collections

results = {'T1':{'team1': 1, 'team2': 3, 'team3': 10}, 'T2': {'team1': 3, 'team2': 1, 'team3': 5}}

def winning_team(results):

team_dict = {}

for tournament, teams in results.items():

for team in teams:

score = teams[team]

if team in team_dict:

team_dict[team] = team_dict[team] + score

else:

team_dict[team] = score

scores = list(team_dict.values())

if len(scores) > len(set(scores)): # check for tie

score_to_compare = [score for score, count in collections.Counter(scores).items() if count > 1]

winning_list = [team for team, score in team_dict.items() if score in score_to_compare]

else:

score_to_compare = max(scores)

winning_list = [team for team, score in team_dict.items() if score == score_to_compare]

return winning_list

0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子