0

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?

2
  • docs.python.org/3/howto/sorting.html Commented Sep 13, 2022 at 22:54
  • @jonrsharpe I've been through these docs already but I am still having hard time understanding how I can satisfy this requirement in just one line. I've done arr.sort(key = lambda x: abs(x)) but that does not satisfy my second requirement Commented Sep 13, 2022 at 22:59

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

This is a common trick in Python. If you want to sort using multiple criteria, have your key function return a tuple.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.