Sorting object attributes in different orders
<p>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.</p>

<pre><code>for team in sorted(teams, key=attrgetter("points", "goalDiff", "scored", "name"), reverse = True):
</code></pre>

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

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

<pre><code>sorted(teams, key=lambda t: (-t.points, -t.goalDiff, -t.scored, t.name))
</code></pre>

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

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

<pre><code>sorted(
    sorted(teams,  key=attrgetter('name')),
    key=attrgetter("points", "goalDiff", "scored"),
    reverse=True)
</code></pre>

python python-3.x sorting