Find the greatest number in a list of numbers

后端 未结 7 1997
我在风中等你
我在风中等你 2020-11-29 02:04

Is there any easy way or function to determine the greatest number in a python list? I could just code it, as I only have three numbers, however it would make the code a lot

相关标签:
7条回答
  • 2020-11-29 02:33

    This approach is without using max() function

    a = [1,2,3,4,6,7,99,88,999]
    max_num = 0
    for i in a:
        if i > max_num:
            max_num = i
    print(max_num)
    

    Also if you want to find the index of the resulting max,

    print(a.index(max_num))
    

    Direct approach by using function max()

    max() function returns the item with the highest value, or the item with the highest value in an iterable

    Example: when you have to find max on integers/numbers

    a = (1, 5, 3, 9)
    print(max(a))
    >> 9
    

    Example: when you have string

    x = max("Mike", "John", "Vicky")
    print(x)
    >> Vicky
    

    It basically returns the name with the highest value, ordered alphabetically.

    0 讨论(0)
  • 2020-11-29 02:42

    You can actually sort it:

    sorted(l,reverse=True)
    

    l = [1, 2, 3]
    sort=sorted(l,reverse=True)
    print(sort)
    

    You get:

    [3,2,1]
    

    But still if want to get the max do:

    print(sort[0])
    

    You get:

    3
    

    if second max:

    print(sort[1])
    

    and so on...

    0 讨论(0)
  • 2020-11-29 02:51

    You can use the inbuilt function max() with multiple arguments:

    print max(1, 2, 3)
    

    or a list:

    list = [1, 2, 3]
    print max(list)
    

    or in fact anything iterable.

    0 讨论(0)
  • 2020-11-29 02:51

    max is a builtin function in python, which is used to get max value from a sequence, i.e (list, tuple, set, etc..)

    print(max([9, 7, 12, 5]))
    
    # prints 12 
    
    0 讨论(0)
  • 2020-11-29 02:54

    What about max()

    highest = max(1, 2, 3)  # or max([1, 2, 3]) for lists
    
    0 讨论(0)
  • 2020-11-29 02:57

    Use max()

    >>> l = [1, 2, 5]
    >>> max(l)
    5
    >>> 
    
    0 讨论(0)
提交回复
热议问题