[英]How to return 1 or -1 if number is positive or negative (including 0)?
我可以问一下如何在Python中实现这一点:
输入: I = [10,-22,0]
输出: O = [1,-1,-1]
我在想O=I/abs(I)
但如何处理零?
以下应该做你想要的:
>>> I = [10,-22,0]
>>> O = [1 if v > 0 else -1 for v in I]
>>> O
[1, -1, -1]
>>>
如果你想使用带有lambda
map
,你可以这样做:
>>> O = map(lambda v: 1 if v > 0 else -1, I)
>>> O
[1, -1, -1]
>>>
你可以这样做:
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.