根据列表python中最接近的数字排序列表

Moh*_*hit 1 python

我想根据列表中的数字与给定数字的接近程度对列表进行排序.例如:

 target_list = [1,2,8,20]
 number = 4

then probably sorted list is [2,1,8,20] 
         as 4-2 = 2
            4-1 = 3
            mod|4-8| = 4
            mod|4-20| = 16
Run Code Online (Sandbox Code Playgroud)

碰撞,我真的不在乎哪一个先来,但后来我试图根据这个距离度量对列表进行排序.什么是最好的(和pythonic)方式来做到这一点.

谢谢

Pra*_*ota 10

您可以使用keysorted功能的参数

>>> target_list = [1,2,8,20]
>>> sorted(target_list, key=lambda x: abs(4-x))
[2, 1, 8, 20]
Run Code Online (Sandbox Code Playgroud)

或者如果你想对它进行排序,即使是list sort方法也接受了key.

>>> target_list.sort(key=lambda x: abs(4-x))
>>> target_list
[2, 1, 8, 20]
Run Code Online (Sandbox Code Playgroud)