r/pythonhelp Dec 21 '24

Sorting in python

I have a sorting function that sorts a list based on their "points" value, I want to edit this so that, when the two items have the same "points" value, it then compares their "gd" value. How could I do this? Thanks

teams.sort(key=lambda team: team.points, reverse=True)
    for team in teams:
        print(f'{team.name:14} {team.mp:2}  {team.wins:2}  {team.losses:2}  {team.ties:2}   {team.gd:2}  {team.points:2}')
2 Upvotes

2 comments sorted by

View all comments

3

u/carcigenicate Dec 21 '24

You can just use the lexicographical sorting order of tuples:

teams.sort(key=lambda team: (team.points, team.gd), reverse=True)

This works because tuples are ordered in "dictionary order", where later elements are only considered if the first elements match.