Invert negative values in a list

后端 未结 5 551
清酒与你
清酒与你 2020-12-11 21:24

I am trying to convert a list that contains negative values, to a list of non-negative values; inverting the negative ones. I have tried abs but it didn\'t work

5条回答
  •  粉色の甜心
    2020-12-11 21:50

    Your attempt didn't work because abs() takes an integer, not a list. To do this, you'll have to either loop through the list:

    x = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
    for i in range(len(x)):
         x[i] = abs(x[i])
    

    Or you can use list comprehension, which is shorter:

    x = [abs(i) for i in x]
    

    Or simply use the built-in map function, which is even shorter :)

    x = list(map(abs, x))
    

    Hope this helps!

提交回复
热议问题