>>> a = [1,4,2,5,3] >>> b = sorted(enumerate(a),key = lambda x:x[1],reverse=True) # reverse参数为True为降序排序 >>> b [(0, 1), (2, 2), (4, 3), (1, 4), (3, 5)] ## index 和 value以tuple的形式返回(ind,value)2. np.argsort()
将list转化为np.array之后用内置函数argsort()得到排序的index
>>> a = np.array([[1, 3 ,2], [6, 5, 4]])
>>> a
array([[1, 3, 2],
[6, 5, 4]])
>>> np.argsort(a, axis=0) #按列排序
array([[0, 0, 0],
[1, 1, 1]], dtype=int64)
>>> np.argsort(x, axis=1) #按行排序
array([[0, 2, 1],
[2, 1, 0]], dtype=int64)
按照抽取的index对原数组排序:
>>> 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])
>>> x[np.argsort(x)][::-1]
array([3, 2, 1])
# 不适用于2-D数组,但可以:
>>> a
array([[1, 3, 2],
[6, 5, 4]])
>>> sorted_ind = np.argsort(a,axis=1)
>>> a[0][sorted_ind[0]]
array([1, 2, 3])
>>> a[0][sorted_ind[0]][::-1] # [::-1]降序排序
array([3, 2, 1])
3. 时间开销对比
a = np.random.randn(9999999)
# Method 1: np.argsort()
t1 = time.time()
sorted_ind = np.argsort(a)
a_sort = a[sorted_ind][::-1]
t2 = time.time()
print('time cost',t2-t1,'s')
# time cost 2.752633571624756 s
# Method 2: list enumerate()
t1 = time.time()
b = sorted(enumerate(a),key = lambda x:x[1])
t2 = time.time()
print('time cost',t2-t1,'s')
#time cost 17.943580627441406 s
np.argsort()显著快于enumerate()方法。



