查找最小或最大降雨量值的指数

时间:2017-04-20 03:02:15

标签: python max min indices

我遇到问题,我的代码会将最小值和最大值显示为月份而不是值。最低和最高的底部代码是占位符,但我不确定如何解决这个问题。

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()

1 个答案:

答案 0 :(得分:1)

因此,要获得minmax值的相应索引,您可以执行以下操作:

index = rainfall.index(min(rainfall))

由于您知道索引将与rain_month列表正确匹配,因此您可以使用该索引查找月份:

print(rain_month[rainfall.index(min(rainfall))])

但是,更好的方法是使用rain_months结构链接您的rainfalldict。由于我们希望订购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]minmax不需要排序列表。此外,如果您执行sort,则更改rainfall的顺序,同时不更改rain_month的顺序,这意味着您无法使用我所描述的第一种方法来获得正确的月。

我的建议是删除sort,或使用第二种方法。