如何根据列表中的项目要求输入?

时间:2019-04-16 20:17:58

标签: python list loops

我正在尝试制作一个循环,询问每个月的降雨量,并将月份存储在列表中。如何通过从列表中拉出每个月来制作1个循环,要求每个月输入降雨?

示例:

months = ["January", "February", "March"]
rainfall = input("What is the rainfall for ", months[0])

每个月我如何进行1次循环?

3 个答案:

答案 0 :(得分:3)

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
rainfall = []
for month in months:
    answer = int(input("What was the rainfall in {}?".format(month)))
    rainfall.append(answer)

答案 1 :(得分:1)

我认为您正在询问字符串格式。有几种方法(%.format()和f字符串),但我最喜欢的是.format(),它看起来像:

months = ["January", "February", "March"]
rainfall = input("What is the rainfall for {}".format(months[0]))

然后重复整个月的过程可能看起来像这样:

months = ["January", "February", "March"]
rainfall = [input("What is the rainfall for {}?\n>>>".format(month)) for month in months]

我在其中添加了一些不错的格式,其中包含\n换行符,并且明显提示了>>>

答案 2 :(得分:0)

您可以使用for循环和列表,该列表将保留用户的降雨答案。 这将循环显示月份列表中的所有元素。

months = ["January", "February", "March"]
rainfalls = []
for month in months:
    rainfall = input("What is the rainfall for " +  month+ "\n")
    rainfalls.append(rainfall)
print(rainfalls) #python3