Python 如何获得列表数字的绝对值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20832769/
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 obtain absolute value of numbers of a list?
提问by Guangyue He
I have a list of number that looks like the one below.
我有一个数字列表,看起来像下面的那个。
[2,3,-3,-2]
How can I obtain a list of value that contain the absolute value of every value in the above list? In this case it would be
如何获取包含上述列表中每个值的绝对值的值列表?在这种情况下,它将是
[2,3,3,2]
采纳答案by thefourtheye
You can use
absandmapfunctions like thismyList = [2,3,-3,-2] print map(abs, myList)Output
[2, 3, 3, 2]Or you can use list comprehension like this
[abs(number) for number in myList]Or you can use list comprehension and a simple if else condition like this
[-number if number < 0 else number for number in myList]
回答by thefourtheye
A list comprehensionwould also work:
一个列表解析也将工作:
>>> lst = [2,3,-3,-2]
>>> [abs(x) for x in lst]
[2, 3, 3, 2]
>>>
回答by hobbs
[ abs(x) for x in list ]would do it.
[ abs(x) for x in list ]会做的。

