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

标签 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

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

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

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

最佳答案

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

sorted(((value, index) for index, value in enumerate(list_of_values)), reverse=True)

在您的示例中,输出为:

[(99, 8), (99, 3), (47, 7), (17, 2), (10, 0), (6, 1), (3, 4), (1, 5), (-3, 6)]

关于在列表中查找最大值(和索引)的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35410523/

相关文章:

arrays - 相同的排序算法,相同的数组,但对同一个数组进行几次排序时给出不同的排序时间

node.js - Mongo自定义多键排序

python - 使用 pandas.read_json 时出现 ValueError

python - 如何对包含混合数字和字符串的 DataFrame 中的数字求和

list - 按第二个元组元素对元组列表进行排序

python - 为什么会超出范围?

python - python数据框中的日期时间索引

arrays - 使用数字作为默认索引

python - 在查询 [INFORMATION_SCHEMA].[TABLES] 时,SQLAlchemy 在插入期间挂起

python - 在 Pandas 循环中合并多个系列