假设n>如何从n个数字的列表中找到k个最大数字. ķ [英] How to find k biggest numbers from a list of n numbers assuming n > k

查看:75
本文介绍了假设n>如何从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包含所有电池-使用

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屋!

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