首页 文章

Python - 在数字列表中查找最大数字

提问于
浏览
70

是否有任何简单的方法或函数来确定python列表中的最大数字?我可以只对它进行编码,因为我只有三个数字,但如果我能用内置函数或其他东西告诉最好的代码,它会使代码更少冗余 .

7 回答

  • 11

    你可以实际排序:

    sorted(l,reverse=True)
    

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

    你得到:

    [3,2,1]
    

    但是如果想要获得最大值:

    print(sort[0])
    

    你得到:

    3
    

    if second max:

    print(sort[1])
    

    等等...

  • 7

    您可以使用带有多个参数的内置函数max()

    print max(1, 2, 3)
    

    或列表:

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

    或者实际上任何可迭代的东西 .

  • 112

    max 是python中的内置函数,用于从序列中获取最大值,即(list,tuple,set等) .

    print(max([9, 7, 12, 5]))
    
    # prints 12
    
  • -4
    #Ask for number input
    first = int(raw_input('Please type a number: '))
    second = int(raw_input('Please type a number: '))
    third = int(raw_input('Please type a number: '))
    fourth = int(raw_input('Please type a number: '))
    fifth = int(raw_input('Please type a number: '))
    sixth = int(raw_input('Please type a number: '))
    seventh = int(raw_input('Please type a number: '))
    eighth = int(raw_input('Please type a number: '))
    ninth = int(raw_input('Please type a number: '))
    tenth = int(raw_input('Please type a number: '))
    
        #create a list for variables
    sorted_list = [first, second, third, fourth, fifth, sixth, seventh, 
                  eighth, ninth, tenth]
    odd_numbers = []
    
        #filter list and add odd numbers to new list
    for value in sorted_list:
        if value%2 != 0:
            odd_numbers.append(value)
    print 'The greatest odd number you typed was:', max(odd_numbers)
    
  • 1

    那么max()怎么样

    highest = max(1, 2, 3)  # or max([1, 2, 3]) for lists
    
  • 6

    如果你必须在不使用max函数的情况下找到它,那么你可以按照下面的代码:

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

    使用 max()

    >>> l = [1, 2, 5]
    >>> max(l)
    5
    >>>
    

相关问题