I want to sort a list based on how close a number in the list is to a given number. So for example:
target_list = [1,2,8,20]
number = 4
then probably sorted list is [2,1,8,20] since:
4-2 = 2
4-1 = 3
|4-8| = 4
|4-20| = 16
In case of collision, I don’t really care which one comes first but then I am trying to sort the list on the basis of this distance metric.
What is the best (and pythonic) way to do this?
You can use the
keyparameter of thesortedfunctionOr if you want to sort it in place, even the list
sortmethod accepts akey.