我们经常遇到排序的问题,而Python处理排序问题时经常使用以下的三个函数,sort(),sorted(),argsort().
list.sort()和sorted()均为Python的内建函数
sort函数的帮助:
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
sort排序时是在原列表中直接排序既改变了原来的列表。
sorted函数的帮助:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
我们可以发现sorted函数是新建一个列表既原列表不动,新增加一个排好序的列表
argsort的帮助文档:
argsort(a, axis=-1, kind='quicksort', order=None)
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified
by the `kind` keyword. It returns an array of indices of the same shape as
`a` that index data along the given axis in sorted order.
argsort()是numpy包下的一个函数,他的返回值是排序的索引值
Demo:
import numpy as np
a = [1,1,2,2,2,33,5,6,7]
b = sorted(a) # 列表a没有改变,列表b为列表a排序的结果
c = np.argsort(a) # 列表a没有改变,返回的值是排序结果的索引
print a,b,c
a.sort() # 列表a发生改变
print a