我遇到问题,我的代码会将最小值和最大值显示为月份而不是值。最低和最高的底部代码是占位符,但我不确定如何解决这个问题。
def main():
#List of months
rain_month = ['January', 'February', 'March',' April', \
'May', 'June', 'July', 'August', \
'September', 'October', 'November', 'December']
#Rainfall list
rainfall = []
#Creates rainfall list for months
index = 0
while index < 12:
print ("Enter rainfall for ", rain_month [index], ": ",sep='', end = '')
amount = float(input())
rainfall.append(amount)
index += 1
print()
#Total Rainfall
total = 0
for value in rainfall:
total += value
print("Total Rainfall:", sep="", end="")
print(format(total, ',.2f'))
#Average Rainfall
average = total / len(rainfall)
print("Average Rainfall: ", sep="", end="")
print(format(average, ',.2f'))
#Sort
rainfall.sort()
print(min(rainfall))
print(max(rainfall))
main()
答案 0 :(得分:1)
因此,要获得min
或max
值的相应索引,您可以执行以下操作:
index = rainfall.index(min(rainfall))
由于您知道索引将与rain_month
列表正确匹配,因此您可以使用该索引查找月份:
print(rain_month[rainfall.index(min(rainfall))])
但是,更好的方法是使用rain_months
结构链接您的rainfall
和dict
。由于我们希望订购dict
,我们应该使用OrderedDict
:
import collections
# This is how OrderedDicts are initalized, you give them a list with (key,value) tuples for the order.
rainfall = collections.OrderedDict(
[('January',0),('Feburary',0)]
)
# Do your computation, something like:
for month in rainfall:
rainfall[month] = input("Rainfall: ")
print(min(rainfall, key=rainfall.get))
print(max(rainfall, key=rainfall.get))
此外,如果您正在执行rainfall.sort()
,则可以从min
获得rainfall[0]
,从max
获得rainfall[-1]
。 min
和max
不需要排序列表。此外,如果您执行sort
,则更改rainfall
的顺序,同时不更改rain_month
的顺序,这意味着您无法使用我所描述的第一种方法来获得正确的月。
我的建议是删除sort
,或使用第二种方法。