2

I have a list of length n.

I want to find the indices that hold the 5 minimum values of this list.

I know how to find the index holding the minimum value using operator

min_index,min_value = min(enumerate(list), key=operator.itemgetter(1))

Can this code be altered to get a list of the 5 indices I am after?

Mongzyy
  • 113
  • 1
  • 8
  • 1
    `sorted(...)[:5]` is the most direct way, not sure there is an optimized version. [related question](http://stackoverflow.com/questions/6910641/how-to-get-indices-of-n-maximum-values-in-a-numpy-array) about numpy arrays – Tadhg McDonald-Jensen May 11 '16 at 12:08
  • This gives the min values, not the indices holding the values. – Mongzyy May 11 '16 at 12:19
  • `sorted(enumerate(list), key=operator.itemgetter(1))[:5]` it uses the same call signature as `min`. – Tadhg McDonald-Jensen May 11 '16 at 12:19
  • If can use `numpy.argpartition`: http://stackoverflow.com/questions/10337533/a-fast-way-to-find-the-largest-n-elements-in-an-numpy-array/20177786#20177786. – Akavall May 11 '16 at 12:21

3 Answers3

1

Although this requires sorting the entire list, you can get a slice of the sorted list:

data = sorted(enumerate(list), key=operator.itemgetter(1))[:5]
Tadhg McDonald-Jensen
  • 17,001
  • 3
  • 29
  • 51
1

what about something like this?

    map(lambda x: [a.index(x),x],sorted(list)[:5])

that will return a list of lists where list[x][0] = the index and list[x][1] = the value

EDIT:

This assumes the list doesn't have repeated minimum values. As adhg McDonald-Jensen pointed out, it this will only return the first instance of the give value.

stackunderflow
  • 202
  • 1
  • 7
1

if use package heapq, it can be done by nsamllest:

heapq.nsmallest(5, enumerate(list), key=operator.itemgetter(1))
Hooting
  • 1,463
  • 10
  • 19