为列表Python中的第n个最大值提供索引号

时间:2016-01-19 18:26:00

标签: python list indexing

使用列表a = [1, 2, 3, 5, 4]我希望找到第n个最大值的索引。 function(a, 4) = 5,因为5是第四大值的索引。注意:需要对包含500个或更多元素的列表起作用并使用循环。

2 个答案:

答案 0 :(得分:0)

如果不使用index和max(最简单的方法),我只会:

def funcion (a):
     highest_value = [0, position]
     for x in range(len(a),0,-1):
         value = a.pop()
         if value > highest_value[0]:
             highest_value[0] = value
             highest_value[1] = len(a)-x
      return highest_value

这样,您将获得最高值并同时保存索引,因此它应该非常有效。使用pop比从0到结尾看快得多,因为访问是向后的。

答案 1 :(得分:0)

我认为你正在使用基于1的索引。假设值是唯一的。

SELECT 
    employeedept as dept_id,
    sum(case when employeedept not in (22,16) then 1 else 0 end) as totalstars,
    count(submitterdept) as totalstarsgiven
FROM 
    Responses
WHERE 
    execoffice_status = 1 and YEAR([approveddate]) = 2015 and month([approveddate]) = 11  
GROUP BY 
    employeedept

会给你5。