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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:19:18  来源:igfitidea点击:

how to obtain absolute value of numbers of a list?

pythonlist

提问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

  1. You can use absand mapfunctions like this

    myList = [2,3,-3,-2]
    print map(abs, myList)
    

    Output

    [2, 3, 3, 2]
    
  2. Or you can use list comprehension like this

    [abs(number) for number in myList]
    
  3. Or you can use list comprehension and a simple if else condition like this

    [-number if number < 0 else number for number in myList]
    
  1. 您可以像这样使用absmap功能

    myList = [2,3,-3,-2]
    print map(abs, myList)
    

    输出

    [2, 3, 3, 2]
    
  2. 或者你可以像这样使用列表理解

    [abs(number) for number in myList]
    
  3. 或者你可以使用列表理解和一个​​简单的 if else 条件

    [-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 ]会做的。