Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd just use <code>itertools.groupby</code>. Something like:</p> <pre><code>top_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))] for u in top_users[0][1]: u.status = 'First prize' for u in top_users[1][1]: u.status = 'Second prize' for u in top_users[2][1]: u.status = 'Third prize' for score, users in top_users[3:]: for u in users: u.status = 'Highly recommended' </code></pre> <p>Or even better, use <code>itertools.count</code> instead of the 4 loops:</p> <pre><code>top_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))] for c, (score, group) in zip(count(0), top_users): if c == 0: prize = 'First prize' elif c == 1: prize = 'Second prize' elif c == 2: prize = 'Third prize' else: prize = 'Highly recommended' map(lambda x: setattr(x, 'status', prize), group) </code></pre> <p>And the last refinement, maybe keep a prize list instead of the if statements.</p> <pre><code>top_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))] prize_list = ['First prize', 'Second prize', 'Third prize', 'Highly recommended'] for c, (score, group) in zip(count(0), top_users): prize = prize_list[c] if c &lt; len(prize_list) else prize_list[-1] map(lambda x: setattr(x, 'status', prize), group) </code></pre> <p>The caveat of this approach is that you're not doing the grouping in the database, but instead you'd be doing it in memory. This may be a problem if there are a lot of users. See <a href="https://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django">How to query as GROUP BY in django?</a> for some guidance on how to do this in the database.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload