Sorting parallel lists in python - first item descending, second item ascending
<p>I have two lists - one for a team name and the second for points </p>

<p>I wanted to sort them based on the points without losing track of the corresponding team. I found something on SO that works great for doing this - and it sorts teams by points in descending order (most to least).</p>

<p>There doesn't appear to be a sort on the second list.</p>

<blockquote>
  <p><strong>EDIT - Original Data</strong></p>
</blockquote>

<pre><code>Teams       Pts
D Clark   0
D Dupuis   2
T Leach   2
J Schutz    0
C Hearder 2
R Pagani  0
M Cameron  2
B Hunter  0
</code></pre>

<p><strong>This is what I'm using:</strong></p>

<pre><code>pts, teams = zip(*sorted(zip(pts, teams), reverse=True))
i = 1
for team, num_pts in zip(teams, pts):
    standings = str(i) + '. ' + team + " ("  + num_pts + ")"
    print standings
    i += 1
</code></pre>

<p><strong>And it results in this:</strong>   </p>

<pre><code>1. T Leach (2)
2. M Cameron (2)
3. D Dupuis (2)
4. C Hearder (2)
5. R Pagani (0)
6. J Schutz (0)
7. D Clark (0)
8. B Hunter (0)
</code></pre>

<p>What I'm trying to do is to add an additional sort on team name - so if there's a tie, then it will <em>sort by names in ascending</em> order, </p>

<p><strong>Like This:</strong>   </p>

<pre><code>1. C Hearder (2)
2. D Dupuis (2)
3. M Cameron (2)
4. T Leach (2)
5. B Hunter (0)
6. D Clark (0)
7. J Schutz (0)
8. R Pagani (0)
</code></pre>

<p>You can specify how <code>sorted</code> will sort by passing in the <code>key</code> kwarg. One handy way to use <code>key</code> is with <code>itemgetter</code> from the <code>operator</code> module.</p>

<p>For example, if you have a list of tuples (such as by zipping two lists) and you want to sort by the second item, then the first, the key would be <code>itemgetter(1,0)</code> so you might do something like this:</p>

<pre><code>from operator import itemgetter
teams_and_points = zip(teams, pts)
for team, points in sorted(points_and_teams, key=itemgetter(1, 0)):
    print(team, points)
</code></pre>

python list python-2.7 sorting