基于单个/耦合函数项排序列表

时间:2017-10-12 16:53:03

标签: python-3.x function sorting

在最近的国际足联预选赛之后,我决定根据一个国家的资格赛结果进行排序排名。这已经发布但我想尝试制作一个。

我制作了以下函数,元素和列表:

def Scores(Country, wins, draws, losses, goalsfor, goalsagainst):
     points = (wins *3)+ draws
     goaldifference = goalsfor - goalsagainst
     return '{} has {} wins, {} draws, {} losses, {} goal difference, {} points'.format(Country, wins, draws, losses, goaldifference, points)

Honduras = Scores('Honduras',3, 4, 3, 13, 19)
Mexico = Scores('Mexico', 6, 3, 1, 16, 7)
CostaRica = Scores('Costa Rica', 4, 4, 2, 14, 8)
TrinidadAndTobago = Scores('Trinidad And Tobago', 2, 0, 8, 7, 19)
USA = Scores('USA', 3, 3, 4, 17, 13)
Panama = Scores('Panama', 3, 4, 3, 9, 10)

Teams = [Honduras, Mexico, CostaRica, TrinidadAndTobago, USA, Panama]

在FIFA中,如果与积分相关,则首先按分数排名,然后按球差进行排名。如何根据这些参数对国家列表进行排序,必须通过该功能达到国家/地区的结果?

预期结果如下: 1)墨西哥 2)哥斯达黎加 3)巴拿马 4)洪都拉斯 5)美国 6)特立尼达和多巴哥

1 个答案:

答案 0 :(得分:1)

这里的class使用total_ordering__eq____lt__的定义可以排序:

from functools import total_ordering

@total_ordering
class Score():
    def __init__(self, country, wins, draws, losses, goals_for, goals_against):
        self.country = country
        self.wins = wins
        self.draws = draws
        self.losses = losses
        self.goals_for = goals_for
        self.goals_against = goals_against

    def _value(self):
        return self.wins * 3 + self.draws, self.goals_for - self.goals_against

    def __eq__(self, other):
        return self._value() == other._value()

    def __lt__(self, other):
        return self._value() < other._value()

Honduras = Score('Honduras',3, 4, 3, 13, 19)
Mexico = Score('Mexico', 6, 3, 1, 16, 7)
CostaRica = Score('Costa Rica', 4, 4, 2, 14, 8)
TrinidadAndTobago = Score('Trinidad And Tobago', 2, 0, 8, 7, 19)
USA = Score('USA', 3, 3, 4, 17, 13)
Panama = Score('Panama', 3, 4, 3, 9, 10)

scores = sorted([Honduras, Mexico, CostaRica, TrinidadAndTobago, USA, Panama], reverse=True)

print([score.country for score in scores])

# Output: ['Mexico', 'Costa Rica', 'Panama', 'Honduras', 'USA', 'Trinidad And Tobago']

<强>更新

这是另一个选项,这次namedtuple中包含keysort功能。 (这使得排序逻辑保持在课堂之外。取决于你正在做什么,这可能更好或更糟。)

from collections import namedtuple
Score = namedtuple('Score',
    ['country', 'wins', 'draws', 'losses', 'goals_for', 'goals_against'])

Honduras = Score('Honduras',3, 4, 3, 13, 19)
Mexico = Score('Mexico', 6, 3, 1, 16, 7)
CostaRica = Score('Costa Rica', 4, 4, 2, 14, 8)
TrinidadAndTobago = Score('Trinidad And Tobago', 2, 0, 8, 7, 19)
USA = Score('USA', 3, 3, 4, 17, 13)
Panama = Score('Panama', 3, 4, 3, 9, 10)

scores = sorted([Honduras, Mexico, CostaRica, TrinidadAndTobago, USA, Panama],
    key=lambda s: (s.wins * 3 + s.draws, s.goals_for - s.goals_against),
    reverse=True)

print([score.country for score in scores])

# Output: ['Mexico', 'Costa Rica', 'Panama', 'Honduras', 'USA', 'Trinidad And Tobago']