Invert negative values in a list

后端 未结 5 547
清酒与你
清酒与你 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:44

    what you want is to use the absolute value (|x| = x if x > 0, |x| = -x if x < 0)

    for index in range(len(x)):
        x[index] =  x[index] if x[index] > 0 else -x[index]
    

提交回复
热议问题