Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find top k largest item of a list in original order in python

say I have the following list:

my_list = [3.5, 1.6, 2.4, 8.9, 5.6]

I want to find the top 3 largest number in its original place, so the result should be:

[3.5, 8.9, 5.6]

How could I do that? I think I can find the 3 largest number and use a filter, but I think it may not be a good idea to compare floats. Any suggestions?

like image 337
Chujun Song Avatar asked Sep 23 '19 21:09

Chujun Song


2 Answers

Use a heap:

>>> import heapq
>>> heapq.nlargest(3, my_list)
[8.9, 5.6, 3.5]

Add a little polish to the same idea, to keep them in original order:

>>> from operator import itemgetter
>>> i_val = heapq.nlargest(3, enumerate(my_list), key=itemgetter(1))
>>> [val for (i, val) in sorted(i_val)]
[3.5, 8.9, 5.6]
like image 93
wim Avatar answered Oct 01 '22 12:10

wim


You can sort the index-value pairs (generated by enumerate) by the value, get the last three pairs, and then sort those by the index (and then get just the values from the index-value pairs, all this in a one-liner list comprehension):

from operator import itemgetter

my_list = [3.5, 1.6, 2.4, 5.6, 8.9]

result = [p[1] for p in sorted(sorted(enumerate(my_list), key = itemgetter(1))[-3:], key = itemgetter(0))]

print(result)

Output:

[3.5, 5.6, 8.9]
like image 21
MrGeek Avatar answered Oct 01 '22 11:10

MrGeek