I have a list below:
arr = [1,3,-10, -4, 4,10,30, -30]
I want to call arr.sort and sort these values based on the absolute value and such that if the absolute values are equal then the negative value should come first like below:
[1, 3, -4, 4, -10, 10, -30, 30]
I know I have a few ways to do this namely wrapping my own class around this and operator overload it. But without this, is there an easier way to do so by just using the key parameter?
CodePudding user response:
You can use a lambda function with a tuple where the 1st value will sort according to the abs value and the second value will sort according to their real value:
In [1]: arr = [1,3,-10, -4, 4,10,30, -30]
In [2]: sorted(arr, key=lambda x: (abs(x), x))
Out[2]: [1, 3, -4, 4, -10, 10, -30, 30]
CodePudding user response:
One approach to this would be to sort the list:
a = [1, 3, -10, -4, 4, 10, 30, -30]
sorted(a)
# [-30, -10, -4, 1, 3, 4, 10, 30]
And then to sort that using abs
as the key.
sorted(sorted(a), key=abs)
# [1, 3, -4, 4, -10, 10, -30, 30]
The first sort serves to move all of the negative numbers to the front. In the second sort, if they're equal, the order is unaffected.