假设n>如何从n个数字的列表中找到k个最大数字. ķ [英] How to find k biggest numbers from a list of n numbers assuming n > k
问题描述
我正在寻找Python中的某些代码,这些代码可以从n
个数字的未排序列表中返回最大k
个数字.首先,我想通过首先对列表进行排序来做到这一点,但这可能会变得非常庞大.
I am looking for some code in Python which could return k
largest numbers from an unsorted list of n
numbers. First I thought to do this by sorting the list first, but this might turn out to be very bulky.
例如,我要从中查找最大数字k
的列表是list1
For example the list from which I want to find k
largest number be list1
> list1 = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
在n = 7
处,如果是k = 3
,即我要从7个数字的列表中找到3个最大的数字,则输出应为0.5, 0.7, 0.5
Here n = 7
and if k = 3
, that is if I want to find 3 largest numbers from a list of 7 numbers then output should be 0.5, 0.7, 0.5
这怎么办?
推荐答案
Python has all batteries included - use heapq
module :)
from heapq import nlargest
data = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
print nlargest(3, data)
比使用整个堆排序还快,因为它使用了部分堆排序
it's also faster than sorting the whole array, because it's using partial heapsort
这篇关于假设n>如何从n个数字的列表中找到k个最大数字. ķ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!