• Python中的排序方法sort(),sorted(),argsort()等


    python 列表排序方法sort、sorted技巧篇

    转自https://www.cnblogs.com/whaben/p/6495702.html,学习参考。

    Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列。

    1)排序基础

    简单的升序排序是非常容易的。只需要调用sorted()方法。它返回一个新的list,新的list的元素基于小于运算符(__lt__)来排序。

    >>> sorted([5, 2, 3, 1, 4])
    [1, 2, 3, 4, 5]

    你也可以使用list.sort()方法来排序,此时list本身将被修改。通常此方法不如sorted()方便,但是如果你不需要保留原来的list,此方法将更有效。

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

    另一个不同就是list.sort()方法仅被定义在list中,相反地sorted()方法对所有的可迭代序列都有效。

    >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
    [1, 2, 3, 4, 5]

    2)key参数/函数

    从python2.4开始,list.sort()和sorted()函数增加了key参数来指定一个函数,此函数将在每个元素比较前被调用。 例如通过key指定的函数来忽略字符串的大小写:

    >>> sorted("This is a test string from Andrew".split(), key=str.lower)
    ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

    key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。这个技术是快速的因为key指定的函数将准确地对每个元素调用。

    更广泛的使用情况是用复杂对象的某些值来对复杂对象的序列排序,例如:

    复制代码
    >>> student_tuples = [
            ('john', 'A', 15),
            ('jane', 'B', 12),
            ('dave', 'B', 10),
    ]
    >>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
    复制代码

    同样的技术对拥有命名属性的复杂对象也适用,例如:

    >>> class Student:
            def __init__(self, name, grade, age):
                    self.name = name
                    self.grade = grade
                    self.age = age
            def __repr__(self):
                    return repr((self.name, self.grade, self.age))
    >>> student_objects = [
            Student('john', 'A', 15),
            Student('jane', 'B', 12),
            Student('dave', 'B', 10),
    ]
    >>> sorted(student_objects, key=lambda student: student.age)   # sort by age
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    3)Operator 模块函数

    上面的key参数的使用非常广泛,因此python提供了一些方便的函数来使得访问方法更加容易和快速。operator模块有itemgetter,attrgetter,从2.6开始还增加了methodcaller方法。使用这些方法,上面的操作将变得更加简洁和快速:

    >>> from operator import itemgetter, attrgetter
    >>> sorted(student_tuples, key=itemgetter(2))
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
    >>> sorted(student_objects, key=attrgetter('age'))
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    operator模块还允许多级的排序,例如,先以grade,然后再以age来排序:

    >>> sorted(student_tuples, key=itemgetter(1,2))
    [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
    >>> sorted(student_objects, key=attrgetter('grade', 'age'))
    [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

    4)升序和降序

    list.sort()和sorted()都接受一个参数reverse(True or False)来表示升序或降序排序。例如对上面的student降序排序如下:

    >>> sorted(student_tuples, key=itemgetter(2), reverse=True)
    [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
    >>> sorted(student_objects, key=attrgetter('age'), reverse=True)
    [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

    5)排序的稳定性和复杂排序

    从python2.2开始,排序被保证为稳定的。意思是说多个元素如果有相同的key,则排序前后他们的先后顺序不变。

    >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
    >>> sorted(data, key=itemgetter(0))
    [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

    注意在排序后'blue'的顺序被保持了,即'blue', 1在'blue', 2的前面。
    更复杂地你可以构建多个步骤来进行更复杂的排序,例如对student数据先以grade降序排列,然后再以age升序排列。

    >>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
    >>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    6)numpy中数组矩阵的排序方法argsort()

    argsort(a, axis=-1, kind='quicksort', order=None)
        Returns the indices that would sort an array.

    从中可以看出argsort函数返回的是数组值从小到大的索引值

    Examples
        --------
        One dimensional array:一维数组

        >>> x = np.array([3, 1, 2])
        >>> np.argsort(x)
        array([1, 2, 0])

        Two-dimensional array:二维数组

        >>> x = np.array([[0, 3], [2, 2]])
        >>> x
        array([[0, 3],
               [2, 2]])
        
        >>> np.argsort(x, axis=0) #按列排序
        array([[0, 1],
               [1, 0]])
        
        >>> np.argsort(x, axis=1) #按行排序
        array([[0, 1],
               [0, 1]])

    例1:

    >>> x = np.array([3, 1, 2])
    >>> np.argsort(x) #按升序排列
    array([1, 2, 0])
    >>> np.argsort(-x) #按降序排列
    array([0, 2, 1])
    
    >>> x[np.argsort(x)] #通过索引值排序后的数组
    array([1, 2, 3])
    >>> x[np.argsort(-x)]
    array([3, 2, 1])

    另一种方式实现按降序排序:

    >>> a = x[np.argsort(x)]
    >>> a
    array([1, 2, 3])
    >>> a[::-1]
    array([3, 2, 1])   
  • 相关阅读:
    IP 排序
    React 项目搭建
    Nuxt
    element table 封装
    iviewui Slider 滑块的坑
    浏览器自动填写用户名和密码
    asd
    正则表达式
    snmp中载入第三方mib库(转载)
    一键lamp
  • 原文地址:https://www.cnblogs.com/zz22--/p/8473901.html
Copyright © 2020-2023  润新知