1

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)
3
  • Belongs the missing ")" to the problem or is it a typo? Commented Jul 28, 2009 at 14:38
  • Can you revert it to the original, wrong version? Otherwise it is confusing. Commented Jul 28, 2009 at 18:31
  • You should accept one of the answers that were useful ;) ;) ;) Commented Jul 29, 2009 at 4:06

2 Answers 2

8

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)
Sign up to request clarification or add additional context in comments.

3 Comments

+1, that's more readable than my answer, and apparently faster: docs.python.org/library/stdtypes.html#typesseq-mutable.
Just added reverse=True to match the original requirement.
operator.attrgetter() is definitely an improvement, pythonically speaking.
1

Try the and-or trick:

lambda x1, y1: x1.created_at < y1.created_at and 1 or -1

1 Comment

The and-or hack is ugly and not necessary anymore. Conditional expressions were introduced precisely to avoid it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.