使用用户定义的函数在Python中排序列表

时间:2018-06-15 08:32:22

标签: python python-3.x list sorting user-defined-functions

sortedL1ist = [2343, 323, 34254, 49, 595]

arr = [2343, 323, 34254, 49, 595]
Like in c++ **:** sort(arr,arr+n,AB)

AB(int x, int y)
{
return (x%10)<(y%10) 
}

如何按照单位数字这个概念在python中实现排序列表?

1 个答案:

答案 0 :(得分:1)

您可以将要排序的键定义为lambda函数,如

some_list = [2343, 323, 34254, 49, 595]
sorted_list = sorted(some_list, key=lambda x : x%10)
print(sorted_list)

输出

[2343, 323, 34254, 595, 49]

你可以使用像这样的比较方法的旧方法

def custom_compare(x, y):
    return x%10 - y%10

print(sorted(some_list, cmp=custom_compare))

这将为您提供相同的输出

注意这只适用于python 2.x版本,key是python 3.x中新的更好的方法