list comprehensions: sorting?

Clark C . Evans cce at clarkevans.com
Wed Sep 5 20:40:01 EDT 2001


As an SQL junkie... I've gotten addicted to 
list comprehensions like... especially in
list of tuples...

 [process(x) for x in mylist if x[4]

I read the above as something like...

 SELECT process(x) FROM mylist AS x WHERE x[4]

What I always want to do is "sort" in this
context, let's say on column two; something
like an ORDER BY clause.  Here is the best
I can think of...

  newlist = [x for x in mylist if x[4]]
  newlist.sort(lambda x,y: cmp(x[2],y[2]))

That's ok... but I'd like to have a nicer way
to say "sort by column #2" ; preferably as part
of the longer expression...

 [process(x) for x in list if x[4] sortdesc x[2] ]

Where "sortdesc" is an expression that I want the
list sorted by descending.  This would make my code
much more readable...

Thoughts?  Any better alternative to what I'm
writing above?

Best,

Clark




More information about the Python-list mailing list