【问题标题】:Dictionary Manupilation字典操作
【发布时间】:2017-02-24 16:13:27
【问题描述】:

我们在一个二级字典中表示一系列比赛中的击球手得分,如下所示:

{'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41 , 'player4':63, 'player3':91}

每场比赛都由一个字符串标识,每个玩家也是如此。分数都是整数。与比赛相关的名字不是固定的(这里它们是'match1'、'match2'、'match3'),球员的名字也不是固定的。球员不需要在所有比赛中记录得分

定义一个 Python 函数“orangecap(d)”,它读取这种形式的字典 d 并识别总分最高的玩家。你的函数应该返回一对 (playername,topscore),其中 playername 是一个字符串,即得分最高的玩家的名字,topscore 是一个整数,即 playername 的总分。

输入将使得最高总分永远不会出现平局。

例如:

orangecap({'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2' :41, 'player4':63, 'player3':91}}) ('player3', 100)

orangecap({'test1':{'Ashwin':84, 'Kohli':120}, 'test2':{'ashwin':59, 'Pujara':42}}) (“科利”,120)

这是我的代码:

def orangecap(d):
s=[]
t=[]
for i in sorted(d.keys()):
    for j in sorted(d[i].keys()):
        flag=0
        for k in range(len(s)):
            if(s[k]==j):
                t[k:k]+=[d[i][j]]
                flag=1
                break
        if(flag==0):
            s.append(j)
            t.append(d[i][j])

m=max(t)
for i in range(len(t)):
    if t[i]==m:
        return (s[i],m)

【问题讨论】:

标签: python


【解决方案1】:

您并没有完全得到问题,以后请尝试具体说明您的要求或尝试https://codereview.stackexchange.com/ 以获得一般指针等。

首先要注意在 python 中,因为在所有编程语言中,在命名变量时都试图尽可能地表达,这将使每个人(通常是你自己)更容易弄清楚发生了什么(和错误)。

所以在这个问题中,我们试图计算出每个玩家的总得分。换句话说,我们将每个匹配的字典组合成一个字典,如果我们有重复的键,则添加。所以

def orangecap(d):

    # Make a new dict to count the totals

    totals = {}

    # Loop over every players score in every match.

    for match in d.values():
        for player in match:

            # Check if player is in totals dictionary. If not add them.

            if player not in totals:
                totals[player] = 0

            # Add players score in this match to there total score.

            totals[player] += match[player]

    #initialise highest_total as we will use it later for comparison.

    highest_total = -1

    #loop through totals to find highest score

    for player in totals:

        # if players score is greater than current highest, set highest_player
        # to be current player, and set the highest total to players total

        if totals[player] >  highest_total:
            highest_player = player
            highest_total = totals[player]

    # return the highest player and highest total

    return highest_player, highest_total

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多