在列表中查找最高值(和索引)的 Pythonic 方法

534*_*534 2 python sorting indexing ranking

我有一个整数列表,我想找到列表中的最高值(最大值和最接近值)及其相应的索引值。

我有一个方法,但我觉得太复杂了!

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
Run Code Online (Sandbox Code Playgroud)

因为列表可能有重复的值(我想保留),所以四个最大值最终可能是“a,a,b,c”。所以我试图同时找到最大值和第二/第三/等最高值。

当我尝试查找索引值时,我认为对列表进行排序不会有帮助。有没有办法保留原始列表的索引,以便如果我从最高到最低对列表进行排序,它也会被修改?

为了清楚起见进行编辑:我可能有 [99,95, 50, 90,99] (多次出现最大值)或 [99, 70, 70, 90,50]。我想做的是找到最高值 - 可能但不一定多次出现最大值。

Tho*_*tze 5

创建一个由值和索引元组组成的可迭代对象(按该顺序)并对其进行排序。对元组进行排序是在第一个元素上完成的(如果相等,则在第二个元素上完成,依此类推):

sorted(((value, index) for index, value in enumerate(list_of_values)), reverse=True)
Run Code Online (Sandbox Code Playgroud)

在您的示例中,输出是:

[(99, 8), (99, 3), (47, 7), (17, 2), (10, 0), (6, 1), (3, 4), (1, 5), (-3, 6)]
Run Code Online (Sandbox Code Playgroud)