如何将此for循环与我的列表连接?

时间:2017-04-12 06:58:52

标签: python-3.x

我正在尝试创建一个执行以下操作的程序,

它“将允许用户将12个月的降雨量统计数据输入到列表中。该程序应计算该年度的总降雨量,该年度的平均降雨量以及降雨量最高和最低的月份。” / p>

其次,“使用循环向用户询问当月的降雨量,并将其存储在列表中的当月适当指数。”

最后,“,你需要设置一个包含月份名称的12个元素的列表。然后你可以使用循环计数器作为月份名称的索引来获得正确的月份。”

这是我到目前为止所拥有的,

months = ['January','February', 
'March','April','May','June','July','August',
       'September','October','November','December']

for i in months:
float(input('What is the rainfall for ' + i + '?'))


print(months)

max_rain = max(months)
min_rain = min(months)
avg_rain = sum(months)/12
print(max_rain)
print(min_rain)
print(avg_rain)

我对如何实现索引计数器感到困惑,正如指示所说的那样,我很遗憾下一步要采取什么步骤。感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:0)

首先,我认为你应该使用dictionaries来达到这个目的,它更适合这项任务。

接下来,如果你正在使用list,在你的循环中,你只需要打印一个值,但不要将输入值放在任何var中。

months = ['January','February', 
'March','April','May','June','July','August',
       'September','October','November','December']

rain = []

for i in months:
    rainfall = (float(input('What is the rainfall for ' + i + '?')))
    while rainfall < 0 :
        print " Rainfall must be >= 0"
        rainfall = (float(input('What is the rainfall for ' + i + '?')))
    rain.append(rainfall)

print(rain)

max_rain = max(rain)
min_rain = min(rain)
avg_rain = sum(rain)/12
print(max_rain)
print(min_rain)
print(avg_rain)

这样你就可以打印出这样的结果。

输出:

What is the rainfall for January?1
What is the rainfall for February?-2
 Rainfall must be >= 0
What is the rainfall for February?-2
 Rainfall must be >= 0
What is the rainfall for February?-2
 Rainfall must be >= 0
What is the rainfall for February?2
What is the rainfall for March?3
What is the rainfall for April?4
What is the rainfall for May?5
What is the rainfall for June?6
What is the rainfall for July?7
What is the rainfall for August?8
What is the rainfall for September?9
What is the rainfall for October?10
What is the rainfall for November?11
What is the rainfall for December?12
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]
12.0
1.0
6.5

我仍然建议你尝试对字典做同样的事情,然后你就可以获得最大的降雨量,并且很容易找到它的月份。

编辑:添加了最后一项要求。

答案 1 :(得分:-1)

你可以替换

for i in months:

for i, month in enumerate(months):

然后你会在循环体中有两个变量: 我用循环计数器和月份来命名。