如何使用循环在列表中找到最大的数?

7

我有一个列表和一些变量:

nums = [14, 8, 9, 16, 3, 11, 5]

big = nums[0]

spot = 0

我对如何实际操作感到困惑。我希望通过这个练习来给自己一个起点。在Python上我该如何做呢?

11个回答

15

通常情况下,您可以直接使用

max(nums)

如果您明确想要使用循环,请尝试:

max_value = None
for n in nums:
    if max_value is None or n > max_value: max_value = n

1
如果列表中有一个数字是“-2”,会怎么样? - alex
1
为循环解决方案添加一些说明:要获取最大的数字,您需要遍历列表并记住迄今为止遇到的最大数字。这样当您到达末尾时,您将记住其中最大的数字。 - poke
1
@alex 你可以设置 max = nums[0];此外,max 不是最好的变量名。 - poke
给定名称max是选择不当。如果列表中的所有数字都< -1,则初始值-1将失败。我已经相应地编辑了帖子。 - helmbert
2
(int) > None 会引发 TypeError。 - poke
显示剩余2条评论

10

给你...

nums = [14, 8, 9, 16, 3, 11, 5]

big = max(nums)
spot = nums.index(big)
这是实现这个功能的Pythonic方式。如果你想使用循环,那么循环当前最大值并检查每个元素是否更大,如果是,则将其分配给当前最大值。

但是没有循环-至少不是显式的。 - tzelleke
@TheodrosZelleke for i in range(len(list)): # for loop iterates through it. 这是一种明确的重复列表长度次数的方法。这适用于索引;如果您想要重复执行x次某些操作,则range()的“end”参数应为x + 1。因此,要重复执行与列表长度相同的x次操作,请执行:for i in range(len(list) + 1): - Rushy Panchal
@F3AR3DLEGEND,感谢您的澄清--然而,我的评论是一种“有点批评”的意思,而不是一个问题。 - tzelleke
对于nums中的每个i,返回nums中的最大值。 :p - Ryan Haining
@F3AR3DLEGEND list 是一个内置函数,最好不要将其作为变量名。你最好使用for i, _ in enumerate(seq)而不是range(len(seq)) - Ryan Haining
@xhainingx 我之前用它来表示它将会是一个列表,而不是用作变量名。尽管如此,我想seq这个名称可能更容易理解。 - Rushy Panchal

9
nums = [14, 8, 9, 16, 3, 11, 5]

big = None

spot = None

for i, v in enumerate(nums):
    if big is None or v > big:
         big = v
         spot = i

1
为了获得额外的分数,请确保在分配 big = nums[0] 之前 nums 不为空,如果为空,则引发异常(ValueError 是一个不错的选择)。 - PaulMcG

2

Python已经内置了这种需求的函数。

list = [3,8,2,9]
max_number = max(list)
print (max_number) # it will print 9 as big number

然而,如果您使用经典的方法找到最大数,可以使用循环。
list = [3,8,2,9]

current_max_number = list[0]
for number in list:
    if number>current_max_number:
        current_max_number = number

print (current_max_number) #it will display 9 as big number

1

OP明确表示他/她希望有一个循环。 - Rushy Panchal

1
回答你的第二个问题,你可以使用一个 for 循环:
for i in range(len(list)):
    # do whatever

你应该注意到range()可以有三个参数:startendstep。Start是从哪个数字开始(如果未提供,则为0);start是包含的。End是结束的位置(必须给出);end是排除的:如果您执行range(100),它将给您0-99。Step也是可选的,它表示要使用的间隔。如果未提供步骤,则为1。例如:
>>> x = range(10, 100, 5) # start at 10, end at 101, and use an interval of 5
>>> x
[10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] # note that it does not hit 100

由于end是不包括的,为了包含100,我们可以这样做:

>>> x = range(10, 101, 5) # start at 10, end at 101, and use an interval of 5
>>> x
[10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] # note that it does hit 100

0

对于列表中的最大值代码HS,我已经使用以下代码成功地使大部分自动评分器工作:

list = [-3,-8,-2,0]

current_max_number = list[0]
for number in list:
    if number>current_max_number:
        current_max_number = number

print current_max_number

def max_int_in_list():
    print "Here"

我不确定max_int_in_list应该放在哪里。它需要恰好1个参数。


2
我不确定max_int_in_list应该放在哪里。它需要正好1个参数。--你是在回答这个问题还是在问一个新的相关问题?Stackoverflow不是一个讨论论坛,它是一个问答网站,所以如果你需要回答跟进问题,你应该删除这个答案,并在这里提问,可能会链接回这个问题作为参考。请参阅:[提问]. - dbc

0

打印列表中最大数的索引。

numbers = [1,2,3,4,5,6,9]

N = 0
for num in range(len(numbers)) :
  if numbers[num] > N :
    N = numbers[num]
print(numbers.index(N))

0

我也会将这个作为参考。你可以先排序,然后打印最后一个数字。

nums = [14, 8, 9, 16, 3, 11, 5]

nums.sort()
print("Highest number is: ", nums[-1])

0
student_scores[1,2,3,4,5,6,7,8,9]

max=student_scores[0]
for n in range(0,len(student_scores)):
  if student_scores[n]>=max:
    max=student_scores[n]
print(max)
# using for loop to go through all items in the list and assign the biggest value to a variable, which was defined as max.

min=student_scores[0]
for n in range(0,len(student_scores)):
  if student_scores[n]<=min:
    min=student_scores[n]
print(min)
# using for loop to go through all items in the list and assign the smallest value to a variable, which was defined as min.

注意:上述代码使用for循环来获取最大值和最小值,这种方法在其他编程语言中也可以常见到。然而,在Python中,使用max()和min()函数是获得相同结果最简单的方法。


欢迎来到StackOverflow。虽然这段代码可能解决了问题,但是包括解释它如何以及为什么解决了问题将有助于提高您的帖子质量,并可能导致更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释,并指出适用的限制和假设。 - Ruli

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