是否有内置的Python函数可以在python.array
numpy.array
{{1}}上执行什么?
答案 0 :(得分:60)
没有内置函数,但很容易用Python提供的优秀工具组装一个:
def argsort(seq):
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
return sorted(range(len(seq)), key=seq.__getitem__)
x = [5,2,1,10]
print(argsort(x))
# [2, 1, 0, 3]
它以相同的方式在Python array.array
上运行:
import array
x = array.array('d', [5, 2, 1, 10])
print(argsort(x))
# [2, 1, 0, 3]
答案 1 :(得分:53)
我计时上面的建议,这是我的结果。
首先,功能:
def f(seq):
# http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3383106#3383106
#non-lambda version by Tony Veijalainen
return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
def g(seq):
# http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3383106#3383106
#lambda version by Tony Veijalainen
return [x for x,y in sorted(enumerate(seq), key = lambda x: x[1])]
def h(seq):
#http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3382369#3382369
#by unutbu
return sorted(range(len(seq)), key=seq.__getitem__)
现在,IPython会话:
In [16]: seq = rand(10000).tolist()
In [17]: %timeit f(seq)
100 loops, best of 3: 10.5 ms per loop
In [18]: %timeit g(seq)
100 loops, best of 3: 8.83 ms per loop
In [19]: %timeit h(seq)
100 loops, best of 3: 6.44 ms per loop
FWIW
答案 2 :(得分:5)
我的枚举选择:
def argsort(seq):
return [x for x,y in sorted(enumerate(seq), key = lambda x: x[1])]
seq=[5,2,1,10]
print(argsort(seq))
# Output:
# [2, 1, 0, 3]
最好使用https://stackoverflow.com/users/9990/marcelo-cantos回答帖子python sort without lambda expressions
的答案[i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
答案 3 :(得分:2)
发现了这个问题,但是需要argsort来获取基于对象属性的对象列表。
扩展unutbu的答案,这将是:
sorted(range(len(seq)), key = lambda x: seq[x].sort_property)