简体   繁体   English

如何找到列表中最大和最小数字的位置?

[英]How to find the position of the maximum and minimum number in a list?

For this assignment I need to write a program that will ask the amount of rainfall for each month.对于这个作业,我需要编写一个程序来询问每个月的降雨量。 The user enters the amount and that gets appended to a list.用户输入金额并将其附加到列表中。 After the data is gathered for each month, the program will calculate and output the total rainfall, average rainfall, the month with the highest rainfall and the month with the lowest rainfall.每月收集数据后,程序将计算并输出总降雨量、平均降雨量、降雨量最高的月份和降雨量最少的月份。 The part I'm having trouble with is returning the months with the highest and lowest rainfall.我遇到问题的部分是返回降雨量最高和最低的月份。 I don't want to use the sort method because I plan on using the maxRain function to go through the rainList to find the highest value and return the position.我不想使用 sort 方法,因为我打算使用 maxRain 函数遍历rainList 来查找最大值并返回位置。 Then in the main function print the month of the corresponding position from the months list.然后在主函数中打印月份列表中对应位置的月份。 Unless there is another way to assign that amount of rainfall to that month and return it another way.除非有另一种方法可以将该月的降雨量分配给该月并以另一种方式返回。

# PURPOSE:  This program lets the user enter the total rainfall for each of
#           of 12 months then calculates total, average, min and max rainfall

months = ["January", "February", "March", "April", 
          "May", "June", "July", "August", 
          "September", "October", "November", "December"]

# function that gets amount of rainfall for each month and appends it to a list
def getRainFall():
    nums = []
    for i in range(len(months)):
        m = months[0+i]
        print("Enter the rainfall for ", m)
        x = input()
        x = float(x)
        nums.append(x)
        
    return nums

# function that adds the numbers of the list and returns the sum
def totalRain(nums):
    total = 0
    for num in nums:
        total = total + num
    return total

# function to calculate and return the average of numbers from a list
def mean(nums):
    total = 0.0
    for num in nums:
        total = total + num
    return total / len(nums)

def maxRain(nums):
    for i in range(len(nums)):
        if nums[i] > nums[i+1]:
            x = nums[i]
        else:
            x = nums[i+1]
    return x
    
#def minRain(nums):
    
def main():
    rainList = getRainFall()
    rainAverage = mean(rainList)
    total = totalRain(rainList)
    highest = maxRain(rainList)
    #lowest = minRain(rainList)
    print("Total rainfall:", total) 
    print("Average rainfall:", rainAverage)
    print("Highest rainfall:", highest)
    #print("Lowest rainfall:", lowest)

    # close the program
    input("Press the <Enter> key to quit")

main()

To answer the core question:回答核心问题:

nums =  [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49,
         37, 19, 40, 41, 31]

list_min, list_max = min(nums), max(nums)

mins = [i for i, j in enumerate(nums) if j == list_min]
maxs = [i for i, j in enumerate(nums) if j == list_max]

print(f'{mins=}, {maxs=}')  $ -> mins=[15], maxs=[9, 12]

So I've altered your code a fair bit, which I don't usually like to do because I think it's less helpful.所以我对你的代码做了一些改动,我通常不喜欢这样做,因为我认为它不太有用。 In this case however it just makes the whole process much simpler.然而,在这种情况下,它只会使整个过程变得更加简单。

This uses builtin python functions to do what you are manually doing.这使用内置的 Python 函数来完成您手动执行的操作。

months = ["January", "February", "March", "April", 
          "May", "June", "July", "August", 
          "September", "October", "November", "December"]

# function that gets amount of rainfall for each month and appends it to a list
def getRainFall():
    nums = []
    for month in months:
        m = month
        print("Enter the rainfall for ", m)
        x = input()
        x = float(x)
        nums.append(x)
        
    return nums
    
def main():
    rainList = getRainFall()
    total = sum(rainList)
    rainAverage = total/len(rainList) # Sum/number of points
    highest = months[rainList.index(max(rainList))] # Max rain index into months arr
    lowest = months[rainList.index(min(rainList))] # Min rain index into months arr
    
    print("Total rainfall:", total) 
    print("Average rainfall:", rainAverage)
    print("Highest rainfall:", highest)
    print("Lowest rainfall:", lowest)

    # close the program
    input("Press the <Enter> key to quit")

main()

Sample output:示例输出:

Enter the rainfall for  January
1
Enter the rainfall for  February
2
Enter the rainfall for  March
3
Enter the rainfall for  April
45
Enter the rainfall for  May
5
Enter the rainfall for  June
6
Enter the rainfall for  July
7
Enter the rainfall for  August
8
Enter the rainfall for  September
9
Enter the rainfall for  October
0
Enter the rainfall for  November
1
Enter the rainfall for  December
2
Total rainfall: 89.0
Average rainfall: 7.416666666666667
Highest rainfall: April
Lowest rainfall: October
Press the <Enter> key to quit

You maxRain does not work because of this nums[i+1] , when i is in the last index you ask for the next and that give you an error, to fix it start you range in 1 (range(1,len(nums)) and change yours [i] for [i-1] and your [i+1] for [i] or end it up on len(nums)-1 to avoid this problem.由于这个nums[i+1] ,你 maxRain 不起作用,当i在最后一个索引中时,你要求下一个并给你一个错误,要修复它,你的范围从 1 (range(1,len(nums) )) 并将您的[i]更改为[i-1]并将您的[i+1]更改为[i]或将其更改为len(nums)-1以避免此问题。

Regarless the above solution you take, in this function you can also keep track of the index and return it with the value, because can return more than one value if you put in inside a tuple or some other object, is a simple as return index,x or return (index,x) if you prefer it with the parenthesis无论您采用上述解决方案,在此函数中,您还可以跟踪索引并将其与值一起返回,因为如果放入元组或其他对象中,则可以返回多个值,就像return index,x简单return index,xreturn (index,x)如果您喜欢带括号的

Alternatively, you can easily use the build-in enumerate alongside a key function to get both the index and the maximum or minimum elements of a given list with max or min或者,您可以轻松地使用内置enumerate与键函数一起使用maxmin给定列表的索引和最大或最小元素

>>> nums=[1,2,34,4,25,0,3]
>>> max(enumerate(nums),key=lambda x:x[1])
(2, 34)#index, element
>>> min(enumerate(nums),key=lambda x:x[1])
(5, 0)
>>> 

a key function is no more than a function that take and elements of your list or iterable (anything that you can call iter on) and extract or transform it into the thing we want it to be compared by, which in the example is...一个关键函数只不过是一个函数,它接受列表中的元素或可迭代的元素(任何你可以调用iter东西)并将其提取或转换成我们希望它进行比较的东西,在示例中是.. .

>>> list(enumerate(nums))
[(0, 1), (1, 2), (2, 34), (3, 4), (4, 25), (5, 0), (6, 3)]
>>> 

...the second element of the tuple we get from enumerate, the lambda part is a way to declare simple anonymous functions so we don't have to do the following and use that instead ...我们从枚举中获得的元组的第二个元素, lambda部分是一种声明简单匿名函数的方法,因此我们不必执行以下操作并改用它

def second_elem(obj):
    return obj[1]

Another thing is that you can use a list directly in a for loop, no need to do it over a range on the len of the list另一件事是您可以直接在 for 循环中使用列表,无需在列表的 len 范围内执行此操作

>>> months = ["January", "February", "March", "April", 
      "May", "June", "July", "August", 
      "September", "October", "November", "December"]
>>> for month in months:
        print(month)

    
January
February
March
April
May
June
July
August
September
October
November
December
>>> 

the same is true for many more object, such as tuple, dict, str, etc, any iterable really对于更多的对象也是如此,例如元组、字典、字符串等,任何可迭代的对象


Your mean and totalRain function aren't wrong but can be make simpler by using the sum function您的meantotalRain函数没有错,但可以通过使用sum函数使其更简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM