【问题标题】:Sort List in Python using user defined function使用用户定义的函数在 Python 中对列表进行排序
【发布时间】:2018-06-15 08:32:22
【问题描述】:
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中实现,比如按照个位数字排序?

【问题讨论】:

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


【解决方案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 中新的更好的方法

【讨论】:

    猜你喜欢
    • 2012-12-21
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    相关资源
    最近更新 更多