[英]Function in python that outputs either -1 or 0 or 1
Is there like a (modified) round function where the output would be either -1,0,1 depending on to what number is the input the closest?是否有像(修改的)圆形 function ,其中 output 将是 -1,0,1 取决于输入最接近的数字? Eg 0 => 0, -2154 => -1, 10 => 1例如0 => 0, -2154 => -1, 10 => 1
Currently I am using normal if else statements:目前我正在使用正常的 if else 语句:
if (i==0):
return 0
elif i > 0:
return 1
else:
return -1
But is there any way how I can make this a one-line code?但是有什么办法可以使它成为单行代码吗? By for instance using some modified round function.例如使用一些修改过的圆形 function。
You can use numpy.sign()
您可以使用numpy.sign()
import numpy as np
print(np.sign(1.2))
print(np.sign(-3.4))
print(np.sign(0))
output: output:
1.0
-1.0
0
Without any imports:没有任何进口:
def sign(i):
return (i>0) - (i<0)
print(sign(1))
print(sign(-3))
print(sign(0))
output: output:
1
-1
0
Here is a one-liner function using plain vanilla python and no imports.这是一个单线 function 使用普通的香草 python 并且没有进口。 It can hardly get simpler than this.几乎没有比这更简单的了。
def f(i):
return -1 if i < 0 else int(bool(i))
In [5]: f(0)
Out[5]: 0
In [6]: f(1)
Out[6]: 1
In [7]: f(-5)
Out[7]: -1
As the other answer commented, you can do it easily by using the numpy.sign()
method, that directly returns your desired result.正如另一个答案评论的那样,您可以使用numpy.sign()
方法轻松完成,该方法直接返回您想要的结果。
However, you can do it directly using the built-in math function and the method copysign(x, y)
, which copies the sign of the second value to the first.但是,您可以直接使用内置数学 function 和方法copysign(x, y)
将第二个值的符号复制到第一个值。 By setting the first value as a boolean it will be interpreted as 0 if the original value is 0, and 1 otherwise.通过将第一个值设置为 boolean,如果原始值为 0,它将被解释为 0,否则为 1。 Then we copy the sign of value, which will transform the 1 into -1 or leave it positive.然后我们复制值的符号,这会将 1 转换为 -1 或保持为正数。
from math import copysign
values = [1, 200, 0, -3, 45, -15]
for value in values:
print(int(copysign(bool(value), value)))
which outputs:输出:
1
1
0
-1
1
-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.