sorting a list with respect to the closest number in the list python

前端 未结 3 1117
一生所求
一生所求 2021-01-24 19:53

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         


        
3条回答
  •  醉梦人生
    2021-01-24 20:55

    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))
    

提交回复
热议问题