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

前端 未结 3 1161
一生所求
一生所求 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:53

    >>> target_list.sort(key=lambda x: abs(number-x))
    >>> target_list
    [2, 1, 8, 20]
    

提交回复
热议问题