Invert negative values in a list

后端 未结 5 546
清酒与你
清酒与你 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 22:10

    This is a wrong answer to your question, but this is what I came here looking for. This is how to invert all the numbers in your list using operator.neg; i.e. also positives to negatives.

    import operator
    x = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
    x = list(map(operator.neg, x))
    

    It returns:

    [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    Or you can do a list comprehension of course:

    x = [-xi for xi in x]
    

提交回复
热议问题