15

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.

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]

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

How can this be done?

4

5 回答 5

31

Python 包含所有电池 - 使用heapq模块 :)

from heapq import nlargest

data = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
print nlargest(3, data)

它也比对整个数组进行排序更快,因为它使用部分堆排序

于 2013-07-28T10:21:03.723 回答
3

可以这样做:

>>> list1
[0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
>>> list2 = list1[:] #make a copy of list1
>>> k = 3
>>> result = []
>>> for i in range(k):
        result.append(max(list2)) #append largest element to list of results
        list2.remove(max(list2)) # remove largest element from old list
>>> result
[0.7, 0.5, 0.5]
>>> 
于 2013-07-28T10:07:48.313 回答
3

假设您不想修改list1,则制作一个排序副本:

In [1]: list1 = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]

In [2]: list2 = sorted(list1)

In [3]: list2
Out[3]: [0.3, 0.3, 0.3, 0.4, 0.5, 0.5, 0.7]

list2中,最大的数字是最后的数字,所以我们将使用切片

In [4]: list2[-3:]
Out[4]: [0.5, 0.5, 0.7]

我添加的链接指向 Pythons文档。作为初学者,您应该从查看教程开始。在那之后,库引用是您最需要的,因为大型标准库是使 python 如此出色的原因之一。

于 2013-07-28T10:11:33.570 回答
2

另一种解决方案:

import numpy as np
k = 3
ind = np.argpartition(list1, -k)[-k:] # index of the k highest elements
print(list1[ind])
于 2019-08-14T10:24:16.897 回答
0

没有排序,使用贪婪的方法

k_largest = list1[:k]
for num in list1:
    for c in range(k):
        if num > k_largest[c]:
            k_largest = k_largest[:c] + [num] + k_largest[c:-1]  # maintains sorted order
            break
print(k_largest)
于 2020-11-24T19:11:14.557 回答