How to turn all numbers in a list into their negative counterparts?

前端 未结 5 595
别跟我提以往
别跟我提以往 2020-12-10 13:48

I am trying to turn a list of positive numbers into a list of negative numbers with the same value in python 3.3.3

For example turning [1,2,3] into

5条回答
  •  半阙折子戏
    2020-12-10 14:16

    There is also this method:

    Little note, this will only work if all numbers start positive. It won't affect 0. If you have negative numbers you don't want changing you need to add the IF statement below.

    if num < 0: continue
    numbers = [1, 2, 3, 4 ,5]
    for num in numbers:
        numbers[num-1] = num - (2*num)
    

    numbers
    [-1, -2, -3, -4, -5]
    

提交回复
热议问题