Python Finding Index of Maximum in List

前端 未结 9 2671
别那么骄傲
别那么骄傲 2021-02-19 01:13
def main():
    a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
    max = 0
    for number in a:
        if number > max:
            max = number
    print max

if __name         


        
相关标签:
9条回答
  • 2021-02-19 02:09

    Use the index(x) function. See the documentation here http://docs.python.org/tutorial/datastructures.html

    def main():
        a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
        max = 0
        for number in a:
            if number > max:
                max = number
        max_index = a.index(max)
        print max
    

    However, this is not as fast as other suggested answers (e.g. using enumerate). Simple though.

    0 讨论(0)
  • 2021-02-19 02:11

    If you like powerfull code you would like this :) If you just have integer numbers you can substitute float by int.

    maximum= max(map(float,[2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]))

    If you have your input in a text file do this:

    file.txt

    2 1 5 234 3 44 7 6 4 5 9 11 12 14 13

    maximum= max(map(float,(open('file.txt', 'r').readline()).split()))

    0 讨论(0)
  • 2021-02-19 02:17

    Update:

    max_idx = -1
    max_val = a[0]
    for i in xrange(1, len(a)):
        if a[i] > max_val:
            max_val = a[i]
            max_idx = i
    

    This doesn't shadow built-in function max(), and also will give correct answers for lists that consist of only negative values.


    Previous solution

    a.index(max(a))
    

    will do the trick.

    Built-in function max(a) will find the maximum value in your list a, and list function index(v) will find the index of value v in your list. By combining them, you get what you are looking for, in this case the index value 3.

    Note that .index() will find the index of the first item in the list that matches, so if you had several identical "max" values, the index returned would be the one for the first.

    For more information:

    • max()
    • index()

    In the spirit of "Simple is better than complex." (Zen of Python)

    0 讨论(0)
提交回复
热议问题