Search code examples
pythonlistsortingfor-loopprimes

is there a way to turn [0, -2, 1, -3, 2, -4, 3, -5, 4, -6] into [0, 1, -2, 2, -3, 3, -4, 4, -5, -6]


In short, I had an assignment problem where my final output should be a list of numbers, However in some cases, I have the good numbers in my list but just in the wrong order. I don't want to change my entire code since it is quite long. Thus, I was wondering if there is a trick, function or something that I can use where I can sort the list in a ascending manner however it doesn't put the negative numbers first.
For example, turn [0, -2, 1, -3, 2, -4, 3, -5, 4, -6] into [0, 1, -2, 2, -3, 3, -4, 4, -5, -6]
Another example, turn [0, 1, 5, 9, -2, 2, -5, -9, -1] into [0, -1, 1, -2, 2, -5, 5, -9, 9]
Another example, turn [12,-12] into [-12,12]
Here you can see that its sorted in an ascending manner but its start from 0 and not from a negative number.


Solution

  • You can use:

    lst = [0, -2, 1, -3, 2, -4, 3, -5, 4, -6]
    print(sorted(lst, key=lambda x: (abs(x), x)))
    

    output

    [0, 1, -2, 2, -3, 3, -4, 4, -5, -6]
    

    Basically you sort the items based on two priorities: first the absolute value of the numbers so that 2 and -2 come next to each other. Also you mentioned, you want -2 to come before 2. The second item of the tuple does this. You are actually comparing tuples. First items are equal so comparison continues to the second items(ascending order):

    lst = [(2, 2), (2, -2)]
    print(sorted(lst)) # [(2, -2), (2, 2)]