Python排序

作者: 关北 | 来源:发表于2019-05-22 11:04 被阅读0次

    一、sort,sorted函数介绍:

    Sort函数是list列表中的函数,而sorted可以对list或者iterator进行排序。

    下面我们使用help来查看他们的用法及功能:
    sort:

    >>> help(list.sort)
    Help on method_descriptor:
    
    sort(...)
        L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
    

    sorted:
    Python3.x:

    >>> help(sorted)
    Help on built-in function sorted in module builtins:
    
    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.
    

    Python2.x:

    >>> help(sorted)
    Help on built-in function sorted in module __builtin__:
    
    sorted(...)
        sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
    

    Python3.x和Python2.x的sorted函数有点不太一样,少了cmp参数。

    二、sort和sorted的比较:

    用sort函数对列表排序时会影响列表本身,而sorted不会。
    举例:

    >>> a = [1,2,1,4,3,5]
    >>> a.sort()
    >>> a
    [1, 1, 2, 3, 4, 5]
    >>> a = [1,2,1,4,3,5]
    >>> sorted(a)
    [1, 1, 2, 3, 4, 5]
    >>> a
    [1, 2, 1, 4, 3, 5]
    

    Python2.x的sorted函数:sorted(iterable,cmp,key,reverse)
    参数:

    • iterable可以是list或者iterator;
    • cmp是带两个参数的比较函数;
    • key 是带一个参数的函数;
    • reverse为False或者True;

    举例说明:
    (1)用cmp函数排序:

    >>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]
    >>> sorted(list1,cmp = lambda x,y: cmp(x[0],y[0]))
    [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
    >>> sorted(list1,cmp = lambda x,y: cmp(x[1],y[1]))
    [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
    

    (2)用key函数排序:

    >>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]
    >>> sorted(list1,key = lambda list1: list1[0])
    [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
    >>> sorted(list1,key = lambda list1: list1[1])
    [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
    

    (3)用reverse排序:

    >>> sorted(list1,reverse = True)
    [('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]
    

    (4)用operator.itemgetter函数排序:

    >>> from operator import itemgetter
    >>> sorted(list1, key=itemgetter(1))
    [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
    >>> sorted(list1, key=itemgetter(0))
    [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
    

    介绍operator.itemgetter函数:

    >>> import operator
    >>> a = [1,2,3]
    >>> b = operator.itemgetter(0)
    >>> b(a)
    

    operator.itemgetter函数获取的不是值,而是定义了一个函数。

    (5)多级排序:

    >>> sorted(list1, key=itemgetter(0,1))
    [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
    

    相关文章

      网友评论

        本文标题:Python排序

        本文链接:https://www.haomeiwen.com/subject/wrfzmqtx.html