在Python中查找数组中最低5个数字的索引

时间:2013-03-18 22:24:34

标签: python

如何找出哪些索引属于数组的最低x(比如5)数?

[10.18398473, 9.95722384, 9.41220631, 9.42846614, 9.7300549 , 9.69949144, 9.86997862, 10.28299122, 9.97274071, 10.08966867, 9.7]

另外,如何直接找到排序的(从低到高)最低x个数字?

4 个答案:

答案 0 :(得分:4)

现有答案很好,但如果你使用numpy,这就是解决方案:

mylist = np.array([10.18398473, 9.95722384, 9.41220631, 9.42846614, 9.7300549 , 9.69949144, 9.86997862, 10.28299122, 9.97274071, 10.08966867, 9.7])
x = 5
lowestx = np.argsort(mylist)[:x]
#array([ 2,  3,  5, 10,  4])

答案 1 :(得分:3)

你可以这样做:

>>> l = [5, 1, 2, 4, 6]
>>> sorted(range(len(l)), key=lambda i: l[i])
[1, 2, 3, 0, 4]

答案 2 :(得分:2)

mylist = [10.18398473, 9.95722384, 9.41220631, 9.42846614, 9.7300549 , 9.69949144, 9.86997862, 10.28299122, 9.97274071, 10.08966867, 9.7]

# lowest 5
lowest = sorted(mylist)[:5]

# indices of lowest 5
lowest_ind = [i for i, v in enumerate(mylist) if v in lowest]

# 5 indices of lowest 5
import operator
lowest_5ind = [i for i, v in sorted(enumerate(mylist), key=operator.itemgetter(1))[:5]]

答案 3 :(得分:0)

[a.index(b) for b in sorted(a)[:5]]
sorted(a)[.x]