[Zope-CMF] sorting lists...

Tres Seaver tseaver@zope.com
28 Mar 2003 06:49:46 -0500


On Fri, 2003-03-28 at 04:46, Antony Higgs wrote:
> Hi
> 
> Using contentValues() to return a list of content, I am left with the
> following...
> 
> [ <Document at /my_folder/doc_a_id>,
> <Document at /my_folder/doc_b_id>,
> <Document at /my_folder/doc_c_id> ]
> 
> Is it possible to sort the list alphabetically on an attribute of each
> Document. ie. on 'Title'?
> 
> ...and if so, how?  ;-)

The naive implementation would be:

  objects = context.contentValues()
  objects.sort( lambda x, y: cmp( x.Title(), y.Title() ) )
  return objects

For a really long list, you may want to create a "decorated"
intermediate (see the Python Cookbook for rationale):

  objects = [ ( x.Title(), x ) for x in context.contentValues() ]
  objects.sort()  # tuples compare "lexicographically"
  return [ x[1] for x in objects ]

Tres.
-- 
===============================================================
Tres Seaver                                tseaver@zope.com
Zope Corporation      "Zope Dealers"       http://www.zope.com