![](/img/trans.png)
[英]Find absolute maximum or minimum at specific position in list by Python
[英]How to find the position of the maximum and minimum number in a list?
对于这个作业,我需要编写一个程序来询问每个月的降雨量。 用户输入金额并将其附加到列表中。 每月收集数据后,程序将计算并输出总降雨量、平均降雨量、降雨量最高的月份和降雨量最少的月份。 我遇到问题的部分是返回降雨量最高和最低的月份。 我不想使用 sort 方法,因为我打算使用 maxRain 函数遍历rainList 来查找最大值并返回位置。 然后在主函数中打印月份列表中对应位置的月份。 除非有另一种方法可以将该月的降雨量分配给该月并以另一种方式返回。
# 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()
回答核心问题:
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]
所以我对你的代码做了一些改动,我通常不喜欢这样做,因为我认为它不太有用。 然而,在这种情况下,它只会使整个过程变得更加简单。
这使用内置的 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()
示例输出:
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
由于这个nums[i+1]
,你 maxRain 不起作用,当i
在最后一个索引中时,你要求下一个并给你一个错误,要修复它,你的范围从 1 (range(1,len(nums) )) 并将您的[i]
更改为[i-1]
并将您的[i+1]
更改为[i]
或将其更改为len(nums)-1
以避免此问题。
无论您采用上述解决方案,在此函数中,您还可以跟踪索引并将其与值一起返回,因为如果放入元组或其他对象中,则可以返回多个值,就像return index,x
简单return index,x
或return (index,x)
如果您喜欢带括号的
或者,您可以轻松地使用内置enumerate
与键函数一起使用max
或min
给定列表的索引和最大或最小元素
>>> 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)
>>>
一个关键函数只不过是一个函数,它接受列表中的元素或可迭代的元素(任何你可以调用iter
东西)并将其提取或转换成我们希望它进行比较的东西,在示例中是.. .
>>> list(enumerate(nums))
[(0, 1), (1, 2), (2, 34), (3, 4), (4, 25), (5, 0), (6, 3)]
>>>
...我们从枚举中获得的元组的第二个元素, lambda部分是一种声明简单匿名函数的方法,因此我们不必执行以下操作并改用它
def second_elem(obj):
return obj[1]
另一件事是您可以直接在 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
>>>
对于更多的对象也是如此,例如元组、字典、字符串等,任何可迭代的对象
您的mean
和totalRain
函数没有错,但可以通过使用sum
函数使其更简单
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.