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
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
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".
The code above is equivalent to:
cmp(x1,x2)
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 ...
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.