如何根据numpy的argsort函数的输出对列表进行排序

时间:2015-07-22 14:45:29

标签: python list sorting numpy

我有一个这样的清单:

 myList = [10,30,40,20,50]

现在我使用numpy's argsort函数来获取排序列表的索引:

import numpy as np
so = np.argsort(myList)

给了我输出:

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

当我想使用so对数组进行排序时,它可以正常工作:

myArray = np.array([1,2,3,4,5])
myArray[so]
array([1, 4, 2, 3, 5])

但是当我将它应用到另一个列表时,它不起作用但会抛出错误

myList2 = [1,2,3,4,5]
myList2[so]
  

TypeError:只有一个元素的整数数组才能转换为   索引

我现在如何使用so排序另一个列表而不使用for-loop并且不首先将此列表转换为数组?

2 个答案:

答案 0 :(得分:3)

myList2是一个普通的python列表,它不支持这种索引。

您需要将其转换为numpy.array,示例 -

In [8]: np.array(myList2)[so]
Out[8]: array([1, 4, 2, 3, 5])

或者你可以使用列表理解 -

In [7]: [myList2[i] for i in so]
Out[7]: [1, 4, 2, 3, 5]

答案 1 :(得分:2)

你做不到。你必须将它转换为数组然后再回来。

myListSorted = list(np.array(myList)[so])

编辑:我运行了一些比较NumPy方式与列表理解的基准。 NumPy快〜27倍

>>> from timeit import timeit
>>> import numpy as np

>>> myList = list(np.random.rand(100))
>>> so = np.argsort(myList) #converts list to NumPy internally
>>> timeit(lambda: [myList2[i] for i in so])
12.29590070003178

>>> myArray = np.random.rand(100)
>>> so = np.argsort(myList)
>>> timeit(lambda: a[o]) 
0.42915570305194706
相关问题