在列表中找到第n个最小的数字? [英] Finding the nth smallest number in a list?

查看:54
本文介绍了在列表中找到第n个最小的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种有效的方法来获取第n个最小的数字及其索引,该列表包含多达15000个实体(因此速度并不是至关重要).

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).

可悲的是,我不能使用numpy或任何其他非标准库.

I sadly can't use numpy or any other non-standard library.

我正在使用Python 2.7

Im using Python 2.7

推荐答案

使用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)]

这篇关于在列表中找到第n个最小的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆