我需要显示降雨量降低10%的月份将低于干旱水平。为此,我创建了两个不同的列表:
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
rainValues = []
我刚刚复制了这段代码,以了解值的存储方式:
enterRain = float(input("Please enter a number in the range 0 to 300"))
rainValues.append(enterRain)
当用户输入并正确显示结果时,我想关联每个值的月份。我用了这段代码:
NearDroughtMonths = []
LowerDroughtMonths = []
for i in range(len(rainValues)):
percentage = rainValues[i] * 0.8
NearDroughtMonths.append(percentage)
for i in range(len(rainValues),len(months)):
if NearDroughtMonths[i] < enterDroughtValue :
LowerDroughtMonths.append(months[i])
if len(LowerDroughtMonths) != 0:
for n in range(len(LowerDroughtMonths)):
print("The months when the rainfall was below the drought level are",LowerDroughtMonths[n],end=",")
elif len(LowerDroughtMonths) == 0:
print("There aren't months when the rainfall was 20% below the drought level")
代码没有给出错误,问题是..它没有正确打印月份,因为我认为这不会将month[x]
与rainValue[x]
相关联..
答案 0 :(得分:0)
因此,我现在很难解决您的代码/问题的结构方式。也就是说,因为您使用相应的i
作为NearDroughtMonths列表的索引,我怀疑这一点:
range(len(rainValues),len(months))
应该是这样的:
range(len(NearDroughtMonths))
编辑:斯图尔特的回答指出你在嵌套循环中使用i
两次,这是正确的,当然可能会导致你的问题。
答案 1 :(得分:0)
看起来你想要这样的东西(我为降雨量和干旱水平做了一些输入)。您需要使用zip将月份与降雨量相关联。
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
monthly_rainfall = [100, 200, 20, 280, 50, 270, 200, 90, 80, 110, 130, 140]
drought_level = 100
drought_months = []
for month, rainfall in zip(months, monthly_rainfall):
if rainfall < drought_level * .8:
drought_months.append(month)
if drought_months:
print ("The months when the rainfall was below the drought level are", ', '.join(drought_months))
else:
print ("There aren't months when the rainfall was 20% below the drought level")
您的代码由于多种原因不起作用 - 缩进似乎错了(也许您在这里错误地粘贴了它?),您使用i
作为变量定义了两个嵌套循环,并尝试迭代{ {1}}这可能是一个空列表。
另外你说你正在寻找几个月,降雨量减少10%将低于干旱水平,但在你的代码中你提到几个月降雨量比干旱水平低20%。我保留了后者。