简体   繁体   English

在列表中找到第n个最小的数字?

[英]Finding the nth smallest number in a list?

i need a efficient way of getting the nth smallest number AND its index in a list containing up to 15000 enties (so speed is not super crucial). 我需要一种有效的方法来获取第n个最小的数字及其索引,该列表包含多达15000个实体(因此速度并不是至关重要的)。

I sadly can't use numpy or any other non-standard library. 可悲的是我不能使用numpy或任何其他非标准库。

Im using Python 2.7 我正在使用Python 2.7

use heapq.nsmallest (and enumerate to get the index): 使用heapq.nsmallest (并enumerate以获得索引):

nums = [random.randint(1,1000000) for _ in range(10000)]

import heapq
import operator

heapq.nsmallest(10,enumerate(nums),key=operator.itemgetter(1))
Out[26]: 
[(5544, 35),
 (1702, 43),
 (6547, 227),
 (1540, 253),
 (4919, 360),
 (7993, 445),
 (1608, 495),
 (5832, 505),
 (1388, 716),
 (5103, 814)]

Use enumerate to store the original position, then sort by the value: 使用enumerate存储原始位置,然后按以下值排序:

original_list = [36, 44, 23, 24, 47, 19, 49, 36, 30, 3]
sorted_lookup = sorted(enumerate(original_list), key=lambda i:i[1])
position, value = sorted_lookup[4] # 4 is my "n"

sorted_lookup in my example is: 我的示例中的sorted_lookup是:

[(9, 3), (5, 19), (2, 23), (3, 24), (8, 30), (0, 36), (7, 36), (1, 44), (4, 47), (6, 49)]

And position is 8 , value is 30 position8value30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM