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])