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

Python 在数字列表中查找最大的数字,python,numbers,max,Python,Numbers,Max,有没有简单的方法或函数来确定python列表中的最大数字?我可以只编码它,因为我只有三个数字,但是如果我可以通过内置函数或其他东西来分辨最大值,那么代码的冗余度就会大大降低。那么max()呢 使用max() 您可以将内置函数与多个参数一起使用: print max(1, 2, 3) 或列表: list = [1, 2, 3] print max(list) 或者事实上是任何令人讨厌的东西 #Ask for number input first = int(raw_input('Ple

有没有简单的方法或函数来确定python列表中的最大数字?我可以只编码它,因为我只有三个数字,但是如果我可以通过内置函数或其他东西来分辨最大值,那么代码的冗余度就会大大降低。

那么
max()呢

使用
max()


您可以将内置函数与多个参数一起使用:

print max(1, 2, 3)
或列表:

list = [1, 2, 3]
print max(list)
或者事实上是任何令人讨厌的东西

    #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)
此方法不使用
max()
函数

此外,如果要查找结果最大值的索引

print(a.index(max_num))
使用函数max()直接接近

函数的作用是:返回具有最高值的项,或者返回iterable中具有最高值的项

示例:当必须查找整数/数字的最大值时

a = (1, 5, 3, 9)
print(max(a))
>> 9
示例:当您有字符串时

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

它基本上返回按字母顺序排列的具有最高值的名称。

max
是python中的内置函数,用于从序列(即列表、元组、集合等)中获取最大值


实际上,您可以对其进行排序:

sorted(l,reverse=True)

你会得到:

[3,2,1]
3
但如果要获得最大值,请执行以下操作:

print(sort[0])
你会得到:

[3,2,1]
3
如果第二个最大值:

print(sort[1])

以此类推……

1)没有理由不为xrange(10)中的u执行我的_列表=排序([int(原始_输入('Please type a number'))与键入额外内容相比。2)你有一个名为“排序列表”的列表,但你实际上没有对其进行排序3)问题中没有任何关于只过滤奇数的问题4)这提供了什么5年前以前的答案没有提供的(除了回答一个没有被问到的问题,并且以一种不那么优雅的方式)为什么你永远不能使用最大值函数呢?所以我为那些准备面试的人写了这篇文章,这里的问题是在不使用最大值函数的情况下找到列表的最大值。如果你觉得这对面试很好,请上传你是否也需要最大值的索引?然后你只需要在for行中包含idx变量。不要不要使用
max
作为变量的名称,因为它是一个内置的名称。还有一个同样有用的方法:将变量命名为默认的内置python关键字是不好的,它会覆盖实际的关键字(您必须知道):-)对列表排序是一个比只获取最大值O(n)更复杂的操作O(n log n)
print(sort[0])
3
print(sort[1])