Index of a local maximum in a list

时间:2018-06-04 17:30:17

标签: python python-3.x

I know that there's a similar problem which was already has answered, but mine is just a little bit different (because it returns the index of the local maximum in a list, instead of the number). So, I do just need an explanation about how should I start my code, since I have no idea about where to start. (Sorry for my English). Thanks.

    def maxloc(xs):
      while True:
        for i in range(len(xs)):
          if xs[i] > xs[i-1] and xs[i] > xs[i+1]:
            big = xs[i]
      return [i]

-x- I've tried again, but the problem now is different. I changed some of my code and the return is always [ ]. Can't understand why. Can ou help me now that I have some code, please?

    def maxloc(xs):
     l1 = []
     for i in range(1, len(xs)-1):
       if xs[i] > xs[i-1] and xs[i] > xs[i+1]:
          l1.append(i)
       return [l1]
     return []

1 个答案:

答案 0 :(得分:0)

This finds the maximum value and then finds its first occurence in the given list

def max_index(my_list)

   max_value = max(my_list)
   max_index = my_list.index(max_value)

return max_index

Here's the expected behaviour.

> list = [1, 2, 3, 4]
> max_index(list)
> 3