python内建argsort
之前只能用numpy
进行argsort。碰巧发现一个不用导入模块的替代方法。
#from operator import itemgetter
import numpy as np
l=np.random.randint(0,10,(4,))
def itemgetter(idx):
def f(x):
return x[idx]
return f
def builtin_argsort(l):
l_pair=zip( range(len(l)), l)
sort_idx = sorted(l_pair, key=itemgetter(1)) # 按键值排序
sort_idx = map(itemgetter(0), sort_idx)
return sort_idx
sort_idx = builtin_argsort(l)
print l, sort_idx, l[sort_idx]
#[8 5 8 5] [1, 3, 0, 2] [5 5 8 8]