Python Finding Index of Maximum in List

前端 未结 9 2669
别那么骄傲
别那么骄傲 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 01:58

    A simple one liner of:

    max( (v, i) for i, v in enumerate(a) )[1]
    

    This avoids having to .index() the list after.

    0 讨论(0)
  • 2021-02-19 01:59

    In my code I would use this:

    >>> max(enumerate(a),key=lambda x: x[1])[0]
    3
    
    0 讨论(0)
  • 2021-02-19 01:59

    You can use enumerate to also give you an index while iterating through a list:

    >>> a = [2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13]
    >>> maxIndex, maxNumber = 0, 0
    >>> for index, number in enumerate(a):
            if number > maxNumber:
                maxIndex = index
                maxNumber = number
    
    >>> maxIndex, maxNumber
    (3, 234)
    
    0 讨论(0)
  • 2021-02-19 02:02

    Use the argmax method of the numpy.array object.

    import numpy as np
    np.array(a).argmax()
    
    0 讨论(0)
  • 2021-02-19 02:06

    If you aren't allowed to use the built in index() function, just iterate with an index, instead of using a foreach loop.

    for i in range(len(a)):
        if a[i] > max:
            max = a[i]
            maxIndex = i
    
    0 讨论(0)
  • 2021-02-19 02:08

    this is way simpler

    x.index(max(x)) #where x is your list
    
    0 讨论(0)
提交回复
热议问题