2

I would like to sort a list of ints, where the desired behavior is

input:  [-2, 1, 4, -5]
output: [1, -2, 4, -5]

Treating it as a list of strings doesn't work, and neither does treating it as a list of ints as they return

string: [-2, -5, 1, 4]
ints:   [-5, -2, 1, 4]

Any pointers on how to received the desired behavior?

2
  • How would you like [-2, 1, 2, -2, 4, -5] to be sorted? [1, 2, -2, -2, 4, -5], [1, -2, -2, 2, 4, -5], or any arbitrary order for number with same abs value? Commented Feb 21, 2018 at 17:53
  • Any arbitrary order with the same abs value is fine :) Commented Feb 21, 2018 at 18:06

2 Answers 2

12

Use a key function that takes the absolute value to create the sort key for each item. Conveniently, Python has such a function built-in: abs().

original = [-2, 1, 4, -5]
original.sort(key=abs)
Sign up to request clarification or add additional context in comments.

2 Comments

My only comment is not to overwrite the reserved name input.
You're right. I did that to match the question, but I changed it.
1

Python allows you to use a custom sort key.
https://www.thegeekstuff.com/2014/06/python-sorted/

I would suggest you define a function that calculates the absolute value (or the second power) of the number, and simply use that as the sort key.

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.