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

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

    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]
    
    0 讨论(0)
  • 2021-01-24 20:53
    >>> target_list.sort(key=lambda x: abs(number-x))
    >>> target_list
    [2, 1, 8, 20]
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题