0

I'm writing a soccer league program and I want to sort the table before printing it out. Each team is a member of a class with certain attributes and so far I've been able to sort the integer attributes correctly.

for team in sorted(teams, key=attrgetter("points", "goalDiff", "scored", "name"), reverse = True):

I want all the attributes except name to be reversed, is there a possible way to "un-reverse" the name attribute in this line of code or do I have to take on a different approach?

2
  • Are the other values numbers? Commented Oct 5, 2016 at 13:53
  • Yes, all attributes except "name" are integers. Commented Oct 5, 2016 at 13:53

1 Answer 1

6

If all attributes (except the name) are numeric, negate those numbers to get a reverse sort for those:

sorted(teams, key=lambda t: (-t.points, -t.goalDiff, -t.scored, t.name))

Negating numbers gives you a way to reverse their sort order without actually having to reverse the sort.

If that's not the case, then you'd have to sort twice, first just by the name attribute (in forward order), then in reverse order by the other attributes. For any object where points, goalDiff and scored are equal, the original sorting order (by name) is retained, because the sort algorithm Python uses is stable:

sorted(
    sorted(teams,  key=attrgetter('name')),
    key=attrgetter("points", "goalDiff", "scored"),
    reverse=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.