On Tue, 2006-10-10 at 15:41 +0100, Tom Smith wrote:
> 
> On 10 Oct 2006, at 15:08, Tom Smith wrote:
> 
> >
> > Sorry for what is probably a simple python question, but if I have a
> > list of Products and I have searched for 100 of them ordered by x...
> >
> > then how do I then sort the QuerySet returned by title?
> >
> > I can't do an .. object_list = products.items().sort('title')
> >
> > because I have already done a [:100] on the results...
> 
> ... answering my own question but this works... probably will be slow  
> for a large collection of objects but it's useful for making a  
> tagcloud (unfinished)..

Time these things before worrying about whether they are too slow. You
are only dealing with 100 items and sorting in Python is a fast
operation. The geniuses behind the code have put a lot of work into
making it go like the wind (on a very windy day). As a general rule, if
you can reduce a Python algorithm to something based on sorting, you are
going to be very happy.

> def tagcloud(request):
> 
>       def sort(objects, sortAttrib):
>               sortValues = [(getattr(objects[i], sortAttrib), i) for i in 
> range 
> (len(objects))]
>               sortValues.sort(), # Sorts by first value in tuple
>               return [objects[sortTuple[1]] for sortTuple in sortValues]
> 
>       words =  Word.objects.all().order_by('value').order_by('- 
> product_count')[:100] # I have calculated these before-hand by  
> splitting product.name into words and creating 2 tables (word and  
> product_word)
>       big_num = words[0].product_count # get the biggest
> 
>       for word in words:
>               word.percentage =  ((word.product_count * 100) / big_num) + 10 
> #  
> the 10 is a hack so the fonts don't disappear....
>       words =  sort(words, 'value') #see above


You can be a little more efficient than this. The built in sort() method
on a list takes an optional comparator function that compares two items
at a time. So you could throw away your sort function and replace it
with

        words = list(words)
        words.sort(lambda lhs, rhs: cmp(lhs.value, rhs.value))
        
which would save a couple of passes over the list. In Python 2.4, you
can also get a little bit more speed using the "key" attribute to sort()
or using the sorted() method (see the Python docs for details on those).

Cheers,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to