Comparison function in Python using Lambdas

I am trying to understand lambdas and I get the idea but how do I define multiple conditions for a Point2 [x,y] comparison, so something like:

if x1 < x2: -1
if x1 == x2: 0
if x1 > x2: 1


The code above is equivalent to:


or in a (ugly) lambda expression:

lambda x1,x2: 1 if x1>x2 else (0 if x1==x2 else -1)

(works only in Python 2.6 and above).

Normally you should use lambda expressions only for functions like

def fun(...):
    return ...

my_compare = lambda x1,x2 : cmp(x1, x2)
my_compare( -100, 100 )

In such a case, lambda expressions aren't usually the best thing. As Jon Skeet mentioned, you're gonna end with multiple if-else expressions:

lambda x1, x2: -1 if x1 < x2 else (0 if x1 == x2 else -1)

For your specific problem:

lambda x1, x2: cmp(x1, x2)

is the way to go.

EDIT: Updated to be real Python according to PEP308 :) Note that the PEP has interesting information about how this should be parenthesized depending on which version of Python you're using. I won't attempt to reproduce it here - just read the PEP!

How about:

-1 if x1 < x2 else (0 if x1 == x2 else 1)

(That's without any knowledge of Python lambda expressions, but it's a fairly common way of expressing this logic in a single expression, which I guess is what you're after.)

EDIT: Others have suggested using cmp - I've been assuming that the questioner actually wants more complicated logic, such as providing their own comparisons, but wants the general form of "choose from a few conditions in a single expression".

Need Your Help

Mysql Insert Into Blob problems

php mysql file-upload

I have a problem when it comes to write the blob (a music file) on to the database. When i try and upload say songA("Nothing else Matter.mp3") it plays some other (the one that i tried to upload some

Context.User is changing to null strangely on Signalr

c# .net signalr

In SignalR, i experience that Context.User is suddenly turning into null value and also it is sometimes completely null but this should never be happen because only Authorized users can access the ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.