[英]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.