Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找列表中第n个最小的数字?_Python_List_Python 2.7 - Fatal编程技术网

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

Python 查找列表中第n个最小的数字?,python,list,python-2.7,Python,List,Python 2.7,我需要一种有效的方法,在一个包含15000个实体的列表中获取第n个最小的数字及其索引(因此速度不是非常关键) 很遗憾,我不能使用numpy或任何其他非标准库 Im使用Python 2.7存储原始位置,然后按值排序: 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 =

我需要一种有效的方法,在一个包含15000个实体的列表中获取第n个最小的数字及其索引(因此速度不是非常关键)

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

Im使用Python 2.7存储原始位置,然后按值排序:

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"
在我的示例中,排序的查找是:

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

位置
8
30

使用
heapq.nsmallest
(和
枚举
获取索引):


但对列表进行排序会丢失其原始属性index@mhlester如果你使用“<代码>排序< <代码> > 10, 10, 10、9, 8、第三最小的列表,可以说是代码>8 < /代码>,而不是<代码> 10 <代码>,我想这是可能的,但我会认为不那么直观的解释。如果OP需要重复数据消除,我会解决它。
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)]