tags:

views:

200

answers:

2

Some python code that keeps throwing up an invalid syntax error:

stat.sort(lambda x1, y1: 1 if x1.created_at < y1.created_at else -1)
+1  A: 

Try the and-or trick:

lambda x1, y1: x1.created_at < y1.created_at and 1 or -1
kgiannakakis
The and-or hack is ugly and not necessary anymore. Conditional expressions were introduced precisely to avoid it.
Roberto Bonvallet
+8  A: 

This is a better solution:

stat.sort(key=lambda x: x.created_at, reverse=True)

Or, to avoid the lambda altogether:

from operator import attrgetter
stat.sort(key=attrgetter('created_at'), reverse=True)
Roberto Bonvallet
+1; I was just about to put that.
JAB
+1, that's more readable than my answer, and apparently faster: http://docs.python.org/library/stdtypes.html#typesseq-mutable.
Bastien Léonard
Just added reverse=True to match the original requirement.
Roberto Bonvallet
operator.attrgetter() is definitely an improvement, pythonically speaking.
hughdbrown