ismail
ismail

Reputation: 3923

What's wrong with this bit of python code using lambda?

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)

Upvotes: 1

Views: 411

Answers (2)

Roberto Bonvallet
Roberto Bonvallet

Reputation: 33319

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)

Upvotes: 8

kgiannakakis
kgiannakakis

Reputation: 104178

Try the and-or trick:

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

Upvotes: 1

Related Questions