I have the following code:
numeros = [-1.4, 2.3, 5.27, -3.5, 2.9, 3.12]
lista = [(x > 0) - (x < 0) for x in numeros]
print(lista)
And it returns the following:
[-1, 1, 1, -1, 1, 1]
The question is what function it fulfills (x > 0) - (x < 0)
and how I could interpret it. Thanks in advance.
If
x
it is positive, then it(x>0)
will beTrue
while(x<0)
will beFalse
, so it(x>0)-(x<0)
will be evaluated asTrue - False
. Since booleans cannot be subtracted, Python will treat them as1 - 0
, and the result will be1
.If
x
it is negative, you can analogously see that the result will be-1
And there is still another case . If
x
it is zero, then both(x>0)
are(x<0)
false, so the result in this case will be0
.So all that expression behaves like a kind of sign function , which python does not have implemented by default (although numpy does implement it ) .
The same using a ternary operator would be
-1 if x<0 else 1 if x>0 else 0
. I personally think this one is clearer, and probably even more efficient.