在一组数字中找到最大的数。

106
7个回答

158

max()怎么样呢?

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

这里还有一个也很有用:找出哪个变量包含最大的数字 - cssyphus

18

这种方法不使用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() 函数返回具有最高值的项,或者在可迭代对象中具有最高值的项。

例如:当您需要在整数/数字上查找最大值时

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

例子:当你有一个字符串时

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

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


2
你为什么不能使用max函数? - Chris Foster
3
所以我写了这篇文章,为那些准备面试的人提供帮助。如果你在面试中遇到了“不使用max函数找出列表中的最大值”的问题,这篇文章可能会对你有所帮助。如果你觉得它对面试有帮助,请点赞。 - Chetan_Vasudevan
2
如果你需要最大值的索引,那么你只需要在for循环中包含idx变量即可。 - Kit Plummer
1
不要将变量命名为 max,因为它是内置函数的名称。 - wjandrea
这不正确,如果列表中只有负数,则最大值max_num设置为0。 - yaozhang
@gamusren 使用 max([n for n in your_list if n<0])。 - Chetan_Vasudevan

18
你可以使用内置函数max()并传入多个参数:
print max(1, 2, 3)

或者一个列表:

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

或者说实际上任何可迭代的内容。


6
将变量命名为默认的Python内置关键词是不好的,这会覆盖实际的关键词(您必须知道这一点):-) - U13-Forward

11

使用max()

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

2
您可以对其进行排序:
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])

and so on...


1
对列表进行排序是一项比仅获取最大值更复杂的操作,其时间复杂度为O(n log n),而获取最大值的时间复杂度为O(n)。 - Allan

2

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

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)

4
  1. 没有理由不这样做:my_list = sorted([int(raw_input('请输入一个数字')) for _ in xrange(10)]),而要输入其他的东西。
  2. 你有一个名为sorted_list的列表,但实际上并没有对它进行排序。
  3. 问题中没有要求仅筛选出奇数。
  4. 除了回答一个未被问及的问题以及使用不太优雅的方式,这提供了什么是过去5年的答案所没有提供的。
- Foon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接