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?
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With