[英]Find indices of x minimum values of a list
I have a list of length n. 我有一个长度为n的清单。
I want to find the indices that hold the 5 minimum values of this list. 我想找到保存此列表的5个最小值的索引。
I know how to find the index holding the minimum value using operator
我知道如何使用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? 可以更改此代码以获得我所追求的5个索引的列表吗?
尽管这需要对整个列表进行排序,但是您可以从sorted
列表中得到一部分:
data = sorted(enumerate(list), key=operator.itemgetter(1))[:5]
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 这将返回一个列表列表,其中list [x] [0] =索引,list [x] [1] =值
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. 正如adhg McDonald-Jensen指出的那样,这只会返回Give值的第一个实例。
如果使用的软件包heapq
,它可以这样做nsamllest
:
heapq.nsmallest(5, enumerate(list), key=operator.itemgetter(1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.