从包含100,000个整数的列表中检索两个最高的项目 [英] Retrieve the two highest item from a list containing 100,000 integers

查看:58
本文介绍了从包含100,000个整数的列表中检索两个最高的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从包含100,000个整数的列表中检索到最高的两个项目,而不必先对整个列表进行排序?

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?

推荐答案

在Python中,使用heapq.nlargest.如果您想处理的不仅仅是头两个元素,这是最灵活的方法.

In Python, use heapq.nlargest. This is the most flexible approach in case you ever want to handle more than just the top two elements.

这是一个例子.

>>> import heapq
>>> import random
>>> x = range(100000)
>>> random.shuffle(x)
>>> heapq.nlargest(2, x)
[99999, 99998]

文档: http://docs.python.org/library/heapq.html#heapq.nlargest

这篇关于从包含100,000个整数的列表中检索两个最高的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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