TestDome 联赛表 - Python

use*_*933 2 python sorting lambda python-2.7

我遇到了一个用Python执行的问题,如下所示:

LeagueTable 类跟踪联赛中每个球员的得分。每场比赛结束后,玩家使用 record_result 函数记录他们的得分。

球员在联赛中的排名是使用以下逻辑计算的:

1.得分最高的玩家排名第一(排名1)。得分最低的玩家排名最后。

2.如果两名选手得分相同,则出场次数最少的选手排名较高。

3.如果两名选手的得分和比赛场数相同,则排名第一的选手排名更高。

实现返回给定排名的玩家的player_rank函数。

    from collections import Counter
    from collections import OrderedDict


    class LeagueTable:
        def __init__(self, players):
            self.standings = OrderedDict([(player, Counter()) for player in players])

        def record_result(self, player, score):
            self.standings[player]['games_played'] += 1
            self.standings[player]['score'] += score

        def player_rank(self, rank):
            return None


    table = LeagueTable(['Mike', 'Chris', 'Arnold'])
    table.record_result('Mike', 2)
    table.record_result('Mike', 3)
    table.record_result('Arnold', 5)
    table.record_result('Chris', 5)
    print(table.player_rank(1))
Run Code Online (Sandbox Code Playgroud)

我为其编写了一个超过 20 行的长解决方案,但随后我发现了该函数的较短代码,如下所示:

    def player_rank(self, rank):
        print(self.standings)
        ranking = sorted(self.standings, key=lambda p: (
        -self.standings[p]['score'], self.standings[p]['games_played'], self.standings[p]['pos']))
        return ranking[rank - 1]
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我理解这是如何工作的吗?

PS:我只是一个新手,刚开始学习编程。

链接到原始问题。

https://www.testdome.com/d/python-interview-questions/9

Lee*_*ong 5

对于解决方案:

def player_rank(self, rank):
    print(self.standings)
    ranking = sorted(self.standings, key=lambda p: (
    -self.standings[p]['score'], self.standings[p]['games_played'], 
self.standings[p]['pos']))
    return ranking[rank - 1]
Run Code Online (Sandbox Code Playgroud)

整个功能基本上都是按照key来对玩家进行排序的,首先

-self.standing[p]['score']
Run Code Online (Sandbox Code Playgroud)

根据“分数”获取降序列表,即从最高到最低,然后

self.standings[p]['games_played']
Run Code Online (Sandbox Code Playgroud)

根据“games_played”将之前的列表再次按升序排序

self.standings[p]['pos']
Run Code Online (Sandbox Code Playgroud)

这个应该根据有序集合的顺序对列表进行排序,我认为您错过了代码中带有“pos”的其他部分

现在你有一个列出了所有排名的列表,你返回具有特定排名的特定玩家