Search code examples
pythonsortingindexingranking

Pythonic way to find highest values (and indexes) in list


I have a list of integers and I want to find the highest values (maximum and closest) in the list and their corresponding index values.

I have one method but I feel that it's too convoluted!

lst = [10,6,17,99,3,1,-3,47, 99]
max_value = (max(lst))
largest = 0.0
largest_index = 0
second_largest = 0.0
second_largest_index = 0
third_largest = 0
third_largest_index = 0
for (index,value) in enumerate (lst):
        if value == largest_value:
            if largest == 0.0:
                largest = value
                largest_index = index
            elif largest != 0.0 and value > second_largest:
                second_largest = value
                second_largest_index= index
            elif second_largest != 0.0 and value > third_largest:
                third_largest = value
                third_largest_index = index
            elif third_largest != 0.0 and value > third_largest:
                fourth_largest = value
                fourth_largest_index = index

        elif value > second_largest and value < largest_value:
            second_largest = value
            second_largest_index = index
        elif value > third_largest and value < second_largest:
            third_largest = value
            third_largest_index = index
        elif value > fourth_largest and value < third_largest:
            fourth_largest = value
            fourth_largest_index = index
    indexlist = [largest_index, second_largest_index, third_largest_index, fourth_largest_index]
return indexlist

Because the list may have duplicate values (which I want to retain), it might be that the four largest values end up being "a,a,b,c". So I'm trying to find both the maximum values and the second/third/etc highest values at the same time.

As I'm trying to find the index values, I don't think that sorting the list would help. Is there a way to retain the index of the original list so that it also gets modified if I sort the list from highest to lowest?

Edit for clarity: It might be the case that I have [99,95, 50, 90,99] (multiple occurences of maximum value) or [99, 70, 70, 90,50]. What I'm trying to do is find the highest values - potentially but not necessarily multiple occurences of a maximum value.


Solution

  • One (maybe overkill) solution but quite clean would be:

    lst = [10, 6, 17, 99, 3, 1, -3, 47, 99]
    meta_lst = list(enumerate(lst))
    

    and then sort by the value (which is the second element)

    from operators import itemgetter
    sorted_meta_lst = sorted(meta_lst, key=itemgetter(1))
    

    You will have a increasing succession of pairs (index in list, value).