简体   繁体   English

如果数字是正数还是负数(包括0),如何返回1或-1?

[英]How to return 1 or -1 if number is positive or negative (including 0)?

Can I ask how to achieve this in Python: 我可以问一下如何在Python中实现这一点:

Input: I = [10,-22,0] 输入: I = [10,-22,0]

Output: O = [1,-1,-1] 输出: O = [1,-1,-1]

I was thinking O=I/abs(I) 我在想O=I/abs(I)

But how to deal with zero? 但如何处理零?

The following should do what you want: 以下应该做你想要的:

>>> I = [10,-22,0]
>>> O = [1 if v > 0 else -1 for v in I]
>>> O
[1, -1, -1]
>>> 

If you want to use map with a lambda , you can do: 如果你想使用带有lambda map ,你可以这样做:

>>> O = map(lambda v: 1 if v > 0 else -1, I)
>>> O
[1, -1, -1]
>>> 

You can just do this: 你可以这样做:

I = [10,-22,0]
output = []

for num in I:
    if num <=0:
        output.append(-1)
    else:
        output.append(1)

print output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM