sort()中key函数的含义和np.argsort()的含义

时间:2015-03-17 22:25:30

标签: python

我想对List进行排序并获得其索引的返回值。

所以我以两种方式做到了,但是他们都给了我错误的结果。我不知道,那有什么问题。

例如:

myList = [2, 1, 7, 3, 6]

我的目标是得到结果:[1,0,4,2,3]

所以第一种方法:

np.array(myList).argsort()

但是我得到了错误的结果:

Out: array([1, 0, 3, 4, 2])

第二种方法:

indices = range[5]
indices.sort(key=myList.__getitem__)

我得到了同样错误的结果:

Out: [1, 0, 3, 4, 2]

我不知道,为什么会这样?

3 个答案:

答案 0 :(得分:2)

这是您的原始列表myList,根据您预期的索引列表与您获得的两个结果进行排序:

的例外:

>>> [myList[each] for each in [1, 0, 4, 2, 3]]
[1, 2, 6, 7, 3]

您的解决方案的结果:

>>> [myList[each] for each in [1, 0, 3, 4, 2]]
[1, 2, 3, 6, 7]

我认为您的解决方案是正确的,您的预期列表不正确。

<强>更新

基于预期结果的解释实际上是输入中每个项目的“排名”,这是一个解决方案:

myList = [2, 1, 7, 3, 6]

def get_rankings(list):
    return [sorted(list).index(each) for each in list]

print get_rankings(myList)
#[1, 0, 4, 2, 3]

答案 1 :(得分:1)

我认为你误解了argsort()的含义。此方法返回一个数组,其中每个索引处的值是属于那里的元素的原始数组中的索引。

例如:

[2,1,7,3,6]

变为: [1,0,3,4,2]

如:

[1] - value = 1

[0] - 值= 2

[3] - value = 3

[4] - 值= 6

[2] - 值= 7

答案 2 :(得分:0)

谢谢大家的回答。我想,我误解了索引。但最初我真的想得到这个结果:[1,0,4,2,3],而不是[1,0,3,4,2]

for myList [2,1,7,3,6]

2 is the second smallest number, corresponds to 1
1 is the first smallest number, corresponds to 0
7 is the fifth smallest number, corresponds to 4
3 is the third smallest number, corresponds to 2
6 is the fourth smallest number, corresponds to 3

所以,这就是为什么我期待[1,0,4,2,3]

我想,现在我可以得到结果,只需执行以下步骤:

indices = np.array(myList).argsort()
[indices.tolist().index(i) for i in range(5)]

所以我会得到预期的结果:[1,0,4,2,3]

相关问题