Python sorted函数

排序的核心是比较两个元素的大小,python中数字排序可以直接使用sorted函数,如果是字符串或者字典,直接比较数学上的大小是没有意义的。因此,比较过程必须通过函数抽象出来。
通常规定,对于两个元素x和y,如果认为x<y,则返回-1,如果认为x==y,则返回0,如果认为x>y,则返回1,这样排序算法就不用关心具体的比较过程,而是根据比较结果直接排序。

print  sorted([36,5,12,9,21])    # ==> [5, 9, 12, 21, 36]

 sorted()函数也是一个高阶函数,它可以接收一个比较函数来实现自定义的排序。
实现倒序排序:

def  reversed_cmp(x,y):
    if x>y:
        return  -1
    if x<y:
        return 1
    return  0

 传入自定义的比较函数reversed_cmp,就可以实现倒序排序

print  sorted([36,5,12,9,21],reversed_cmp)   # ==>[36, 21, 12, 9, 5]

 默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。

print  sorted(['bob', 'about', 'Zoo', 'Credit'])   # ==> ['Credit', 'Zoo', 'about', 'bob']

 忽略大小写的比较算法:

def   cmp_ignore_case(s1,s2):
    u1=s1.upper()
    u2=s2.upper()
    if  u1<u2:
        return  -1
    if u1>u2:
        return  1
    return 0
    
print  sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
#['about', 'bob', 'Credit', 'Zoo']
原文地址:https://www.cnblogs.com/zwgblog/p/7201277.html