Python:从某些列表中获取最多N个元素 [英] Python: take max N elements from some list

查看:370
本文介绍了Python:从某些列表中获取最多N个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些函数可以返回某些列表中的N个最高元素?

Is there some function which would return me the N highest elements from some list?

即如果max(l)返回单个最高元素sth.就像max(l, count=10)会给我返回10个最高数字的列表(如果l较小则更少).

I.e. if max(l) returns the single highest element, sth. like max(l, count=10) would return me a list of the 10 highest numbers (or less if l is smaller).

或者,获得这些有效的简便方法是什么? (除了明显的规范实现;而且,没有这样的事情需要首先对整个列表进行排序,因为与规范解决方案相比效率不高.)

Or what would be an efficient easy way to get these? (Except the obvious canonical implementation; also, no such things which involve sorting the whole list first because that would be inefficient compared to the canonical solution.)

推荐答案

heapq.nlargest :

>>> import heapq, random
>>> heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100)))
[1.9730767232998481, 1.9326532289091407, 1.7762926716966254]

这篇关于Python:从某些列表中获取最多N个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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