【python】排序

排序

内置sorted排序

sorted(iterable, /, *, key=None, reverse=False)
    '''
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.xxxxxxxxxx A custom key function can be supplied to customize the sort order, and thereverse flag can be set to request the result in descending order.
    '''

参数解释:

  1. iterable 可迭代对象

  2. key 函数

    key函数的返回值就是排序依据

  • 内建函数

    注意:只需要函数名即可,没有括号,如:

    a = ['1','2', '3', '10']
    sorted(a)
    Out[3]: ['1', '10', '2', '3']
    sorted(a, key=int)
    Out[4]: ['1', '2', '3', '10']
    

    其实就是我们对可迭代对象的每一个元素进行int(),再将执行完后的结果进行排序

  • 自定义函数

    可使用匿名函数 lambda表达式如:

    a = [{'value':100}, {'value':80}, {'value':60}]
    sorted(a,key=lambda x:x['value'])
    Out[7]: [{'value': 60}, {'value': 80}, {'value': 100}]
    # 按每个元素的key ‘value’的值来排序
    

    一种比lambda效率高的方式

    a = [{'value':100}, {'value':80}, {'value':60}]
    from operator import itemgetter
    sorted(a,key=itemgetter('value'))
    Out[11]: [{'value': 60}, {'value': 80}, {'value': 100}]
    

    operator 模块提供了一套与Python的内置运算符对应的高效率函数

  • key 的优先级

    key 可以有多个条件,相应的key函数的返回值也要多个(一般建议元组)

    返回值按照优先级排序,从前到后优先级依次降低

    方案是进行多次排序,有几个返回值就排序几次,优先级低的字段先排序,然后逐个根据优先级高的字段排序,如

    a = ['51','12', '23', '53']
    sorted(a)
    Out[17]: ['12', '23', '51', '53']
    sorted(a, key=lambda x:[x[1],x[0]]) # x[0]优先级低, x[1]优先级高
    Out[18]: ['51', '12', '23', '53']
    

    也可以理解为先按高优先级的排序,如果高优先级相同的情况下,再依次按低优先级来排

posted @ 2021-11-21 22:50  倒骑驴子  阅读(7)  评论(0编辑  收藏  举报