Python - Find the greatest number in a list of numbers

柔情痞子 提交于 2019-12-17 07:15:40

问题


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 less redundant if I could tell the greatest with a built in function or something.


回答1:


What about max()

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



回答2:


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.




回答3:


This approach is without using max() function

If you have to find it without using max function then you can follow the code below:

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

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

print(a.index(max))



回答4:


Use max()

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



回答5:


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...




回答6:


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 



回答7:


    #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)


来源:https://stackoverflow.com/questions/3090175/python-find-the-greatest-number-in-a-list-of-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!