我的计划应该采取每个月的降雨量并计算一年中的总降雨量,平均每月降雨量以及具有最高(最高)和最低(最低)降雨量的月份。
除最高月份和最低月份产出外,一切都按计划进行。我需要这个来显示降雨量最高和最低的月份名称。我可以显示正确的值,而不是月份的名称。
months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]
values = []
year = []
for i in months :
values.append(float(input("Enter total rain for " + i + ": ")))
print()
def total():
print("The total rainfall for the year is %.2f" % sum(values))
total()
def average():
print("The average monthly rainfall is %.2f" % float(sum(values)/ 12))
average()
def highest():
print("The highest monthly rainfall is", max(values))
highest()
def lowest():
print("The lowest monthly rainfall is", min(values))
lowest()
答案 0 :(得分:1)
values
months
min
可以获得max
或(value, month)
,>>> months = ["January", "February", "March", "April",
... "May", "June", "July", "August",
... "September", "October", "November", "December"]
>>> values = [47, 2, 28, 9, 4, 64, 28, 94, 1, 9, 4, 23] # or whatever
>>> val, month = min(zip(values, months))
>>> print("The lowest rainfall was %r in %s" % (val, month))
The lowest rainfall was 1 in September
的元组。确保将值放在第一位,以便用于排序。
php_admin_value open_basedir
答案 1 :(得分:0)
您可以找到最小值/最大值的索引,然后使用该索引查找月份。使用zip是更加pythonic的方式,但这是另一个初学者的方法
def highest():
print("The highest rainfall month is:",months[values.index(max(values))] )
print("The highest monthly rainfall is", max(values))
答案 2 :(得分:0)
max
和min
分别返回列表中的最大值或最小值。您可以使用index
获取该值的索引,然后使用索引获取月份名称。 E.g:
def highest():
max_value = max(values)
ind = values.index(max_value)
month_name = months[ind]
print("The highest monthly rainfall is %d, occurring on %s" % \
(max_value, month_name))