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

use*_*945 3 python list python-2.7

我需要一种有效的方法来获得包含多达15000个内容的列表中的第n个最小数字及其索引(因此速度不是非常关键).

我遗憾地不能使用numpy或任何其他非标准库.

我使用的是Python 2.7

roi*_*ppi 5

使用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)]
Run Code Online (Sandbox Code Playgroud)