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?
heapq
module provides a number of utility functions that may or may not be implemented with heaps; the current implementation ofnlargest
usually uses a heap under the hood, but not always (as it happens, it probably shouldn't use heaps as often as it does, assorted
is typically more efficient if most of the results would be kept). Up-voted regardless; this is whatnlargest
exists for, and this has some of the cleanest examples of decorating and undecorating. – Cripps