find the maximum number in a list using a loop

后端 未结 10 1534
野趣味
野趣味 2021-01-02 23:16

So I have this list and variables:

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

big = nums[0]

spot = 0

I\'m confused on how to actually do it. Please

相关标签:
10条回答
  • 2021-01-03 00:06
    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.
    

    Note: the above code is to pick up the max and min by using for loop, which can be commonly used in other programming languages as well. However, the max() and min() functions are the easiest way to use in Python to get the same results.

    0 讨论(0)
  • 2021-01-03 00:07

    Here you go...

    nums = [14, 8, 9, 16, 3, 11, 5]
    
    big = max(nums)
    spot = nums.index(big)
    

    This would be the Pythonic way of achieving this. If you want to use a loop, then loop with the current max value and check if each element is larger, and if so, assign to the current max.

    0 讨论(0)
  • 2021-01-03 00:15
    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
    
    0 讨论(0)
  • 2021-01-03 00:16

    Usually, you could just use

    max(nums)
    

    If you explicitly want to use a loop, try:

    max_value = None
    for n in nums:
        if n > max_value: max_value = n
    
    0 讨论(0)
提交回复
热议问题