Python 词典输出未按预期打印

Python dictionaries output not printing as expected

问题如下:每场比赛有两支队伍进行比赛。在所有这些比赛中将有一个赢家和一个输家,没有平局。每个团队将与所有其他团队竞争一次。一支球队每赢一场比赛得 3 分,每输一场比赛得 0 分。保证比赛总是至少有两支球队,并且只有一名冠军。

我们有两个输入,比赛数组和结果数组。我们需要编写一个函数,returns 锦标赛的获胜者,或者更具体地说,拥有最多 points.we 的球队的名称有两个字符串:第一个是主队,第二个是客队的名称。结果数组代表每场比赛的获胜者。在结果数组中,1 表示主队获胜,0 表示客队获胜。结果数组与竞赛数组长度相同,结果数组中的索引与竞赛数组中的索引相对应。

    def tournamentWinner(competitions, results):
        # Write your code here.
        
            d = {}
            for i in range(len(results)):
                if results[i] == 0:
                    if competitions[i][1] not in d:
                        d[competitions[i][1]]  = 3
                    else:
                        d[competitions[i][1]]  += 3
                elif results[i] == 1:
                    if competitions[i][0] not in d:
                        competitions[i][0] = 3
                    else:
                        d[competitions[i][0]] += 3
    
            print(max(d,key=d.get))

tournamentWinner([
    ["HTML", "Java"],
    ["Java", "Python"],
    ["Python", "HTML"],
    ["C#", "Python"],
    ["Java", "C#"],
    ["C#", "HTML"]
  ],[0, 1, 1, 1, 0, 1])

输出应该是 C#,但根据我的代码,我得到 Java。有人可以指导我完成这个吗?

您忘记了 d 的一个索引,因此 home-wins 永远不会添加到您的词典中:

def tournamentWinner(competitions, results):         
        d = {}
        for i in range(len(results)):
            if results[i] == 0:
                if competitions[i][1] not in d:
                    d[competitions[i][1]]  = 3
                else:
                    d[competitions[i][1]]  += 3
            elif results[i] == 1:
                if competitions[i][0] not in d:
                    competitions[i][0] = 3   # HERE missing d[...] = 3
                else:
                    d[competitions[i][0]] += 3

        print(d) # => {'Java': 6, 'C#': 6} - theres smth missing ;)
        print(max(d,key=d.get))

在返回结果之前单步执行或打印出 d 即可轻松查看。


你可以简化这个(改为返回结果而不是打印):

def tournamentWinner(competitions, results):
    d = {}
    for teams,result in zip(competitions,results):
        # teams is a list of 2 elements, result is 0 or 1:
        # the winner is the index into the 2-elem-list by 1-result
        winner = teams[1-result] # [home,far], 1 == home wins
        d.setdefault(winner,0) # create key with 0 if not there
        d[winner] += 1 # no need to add up 3 - the points are never used

    print(d) # ==>  {'Java': 2, 'Python': 1, 'C#': 3}
    return max(d.items(), key=lambda tup:tup[1]) [0] # select the key


result = tournamentWinner([
["HTML", "Java"],
["Java", "Python"],
["Python", "HTML"],
["C#", "Python"],
["Java", "C#"],
["C#", "HTML"]
],[0, 1, 1, 1, 0, 1])

print(result)

产出

C#

在任何平局中,结果只会显示获得该分数的第一支球队 - 您可以解决这个问题,但任务没有告诉您,所以不需要。

您的违规线路位于

 competitions[i][0] = 3

你修改比赛而不是记分牌的地方,你应该在那里

 d[competitions[i][0]] = 3

我提出以下可能更容易理解的 计算整个记分牌:

  • 显式变量
  • 边缘案例处理(记分牌中缺少球队)。
def get_winner_in_score_board(score_board):
    return max(score_board, key=score_board.get)


def tournament_winner(competitions, results):
    score_board = {}
    for competitors, result in zip(competitions, results):
        if result == 1:
            loser = competitors[1]
            winner = competitors[0]
        else:
            loser = competitors[0]
            winner = competitors[1]

        try:
            score_board[winner] += 3
        except KeyError:
            score_board[winner] = 3

    return get_winner_in_score_board(score_board)


tournament_winner(
    [
        ["HTML", "Java"],
        ["Java", "Python"],
        ["Python", "HTML"],
        ["C#", "Python"],
        ["Java", "C#"],
        ["C#", "HTML"],
    ],
    [0, 1, 1, 1, 0, 1],
)

请注意,至少一次未获胜的球队不会出现在记分牌中。也许我们也想拥有它们,对此有不同的解决方案,但由于您似乎只想要获胜者,所以我没有添加它。