Python 如何将负数转换为正数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3854310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a negative number to positive?
提问by aneuryzm
How can I convert a negative number to positive in Python? (And keep a positive one.)
如何在 Python 中将负数转换为正数?(并保持积极的态度。)
采纳答案by aneuryzm
回答by BoltClock
If "keep a positive one"means you want a positive number to stay positive, but also convert a negative number to positive, use abs():
如果“保持正数”意味着您希望正数保持正数,但也将负数转换为正数,请使用abs():
>>> abs(-1)
1
>>> abs(1)
1
回答by Tim
The inbuilt function abs() would do the trick.
内置函数 abs() 可以解决问题。
positivenum = abs(negativenum)
回答by Tauquir
In [6]: x = -2
In [7]: x
Out[7]: -2
In [8]: abs(x)
Out[8]: 2
Actually abswill return the absolute valueof any number. Absolute value is always a non-negative number.
实际上abs会返回absolute value任何数字的。绝对值始终是非负数。
回答by Jeroen Dierckx
simply multiplying by -1 works in both ways ...
简单地乘以 -1 有两种方式......
>>> -10 * -1
10
>>> 10 * -1
-10
回答by Pratik Jayarao
If you are working with numpy you can use
如果您正在使用 numpy,则可以使用
import numpy as np
np.abs(-1.23)
>> 1.23
It will provide absolute values.
它将提供绝对值。

