[Tutor] sorting objects in lists by 2 attr

Eric Brunson brunson at brunson.com
Mon Jul 23 19:28:29 CEST 2007


Philippe Niquille wrote:
>
> Hi
>
>
> I have a hard time sorting an object list. Perhaps this is kind of a 
> noob question, but I would very much appreciate any help!
>
>
> Using django I get a QuerySet of Score objects which are sorted by the 
> actual score, the actual score divided by the max. possible score (so 
> sorting by two db fields).
>
> I then need to loop through that queryset and sum up all the score 
> objects which belong to the same user into one Score objects. This 
> works (see code below).
>
>
> The problem I now have, is that I lost the sorting order, as described 
> above. How would I resort it with a python algortithm instead of SQL?
>

This is not the question you're asking, but my first though was, why not 
have SQL do the summing for you using sum() and group by?

>
> scores = Score.objects.order_by('score', 'score2','owner') # filter by 
> course, MC !!
>
> # loop through scores to regroup by user
>
> newscore = []
>
> for s in scores:
>
> i = False
>
> # loop through new object container and check for existant user index, 
> add scores if existant
>
> for ns in newscore:
>
> if s.owner == ns.owner:
>
> ns.score = int(ns.score) + int(s.score)
>
> ns.maxscore = int(ns.maxscore) + int(s.maxscore)
>
> i = True
>
> # otherwise append new user index object, work with it later, perhaps 
> (if more user objects exist)
>
> if i == False:
>
> newscore.append(s)
>
>
> -----------------
>
>
> I did fiddle around with .sort() but didn't get any useful results 
> (and it would only sort by one object..).
>
>
> class CmpAttr:
>
> def __init__(self, attr):
>
> self.attr = attr
>
> def __call__(self, x, y):
>
> return cmp(getattr(x, self.attr), getattr(y, self.attr))
>
>
> newscore.sort(CmpAttr("score"))
>
>
>
> ps. could it be, that this maillist is blocking some e-mail addresses?
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list