如何轻松找到给定数字列表中的最大数字?
怎么样
max()
highest = max(1, 2, 3) # or max([1, 2, 3]) for lists
这种方法没有使用
功能max()
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)
另外,如果你想找到结果最大值的索引,
print(a.index(max_num))
使用函数 max() 的直接方法
max() 函数返回具有最高值的项,或 iterable 中具有最高值的项
示例:当您必须在整数/数字上找到最大值
a = (1, 5, 3, 9)
print(max(a))
>> 9
例子:当你有字符串
x = max("Mike", "John", "Vicky")
print(x)
>> Vicky
它基本上返回具有最高值的名称,按字母顺序排列。
使用
max()
>>> l = [1, 2, 5]
>>> max(l)
5
>>>
max
是 python 中的内置函数,用于从序列中获取最大值,即(列表、元组、集合等)
print(max([9, 7, 12, 5]))
# prints 12
您实际上可以对它进行排序:
sorted(l,reverse=True)
l = [1, 2, 3]
sort=sorted(l,reverse=True)
print(sort)
你得到:
[3,2,1]
但是如果想获得最大的收益,请执行以下操作:
print(sort[0])
你得到:
3
如果第二个最大值:
print(sort[1])
等等……
#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)