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 l
You can use the key
parameter of the sorted
function
>>> target_list = [1,2,8,20]
>>> sorted(target_list, key=lambda x: abs(4-x))
[2, 1, 8, 20]
Or if you want to sort it in place, even the list sort
method accepts a key
.
>>> target_list.sort(key=lambda x: abs(4-x))
>>> target_list
[2, 1, 8, 20]
>>> target_list.sort(key=lambda x: abs(number-x))
>>> target_list
[2, 1, 8, 20]
sorted(target_list, key=lambda k: abs(k - 4))
Or to sort the list in place:
target_list.sort(key=lambda k: abs(k - 4))