简体   繁体   English

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

[英]How can I ask for input based on items in a list?

I'm trying to make a loop that asks for the rainfall of each month, with the months stored into a list. 我正在尝试制作一个循环,要求每个月的降雨量,并将月份存储在列表中。 How can I make 1 loop that will ask for input of the rainfall for each month by pulling each month from the list? 如何通过从列表中拉出每个月来制作1个循环,要求每个月输入降雨?

example: 例:

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

how can i do that for each month with 1 loop? 我该如何每月进行1次循环?

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)

I think you are asking about string formatting. 我认为您正在询问字符串格式。 There are several ways ( % , .format() , and f-strings), but my favorite would be .format() which would look like: 有几种方法( % .format()和f字符串),但我最喜欢的是.format() ,它看起来像:

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

Then to repeat the process for all months would could look something like this: 然后,重复整个月的过程可能看起来像这样:

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

Where I added some nice formatting with a \\n newline character, and an obvious prompt of >>> 我在其中添加了一些不错的格式,其中带有\\n换行符,并且明显提示>>>

You can use a for loop and a list that will keep taken rainfall answers from user. 您可以使用for循环和列表,该列表将保留用户的降雨答案。 This will loop for all elements in months list. 这将循环显示月份列表中的所有元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 输入错误时,如何再次请求相同的输入? - How can I ask for the same input again when there was incorrect input? 如何根据涉及 python 中多个列表项的规则合并列表中的项? - How can I merge items in a list based on a rule that involves multiple list items in python? 如何通过 Windows 中的终端在 python 中请求用户输入? - How can I ask for user input in python through the terminal in windows? 如何同时要求浮点输入和整数? - How can I ask for a float input and an integer at the same time? 如何在条件后要求用户输入? - How can I ask the user for an input after a conditional? 如何基于单个输入创建列表 - How can i create a list based on a single input 如何根据条件将用户输入排序到列表中 - How can i sort user input into a list based on conditionals 在项目列表上切换最喜欢的项目 - 我如何在不使用提交的情况下由用户自动保存项目<input> - Toggling favorite item(s) on a list of items - how can i autosave items by the user, without using a submit <input> 如何让setup.py列出依赖项? - How can I ask setup.py to list dependencies? 如何创建一个新列表,其中每个列表都基于主列表中的项目索引? - How can I make a new list where each list is based on an items index in the main list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM