如何让用户从列表中提取数据并将其清晰地显示在输出中?

How to have a user pull data from lists and display it cleanly in output?

我有一个 table 包含给定的一年月平均温度,我需要开发一些 python 代码,允许用户 select 一个月并拥有 selected 月份和相应的月​​平均温度打印在屏幕上,输出如下:

The average temperature in New York in March is 10.0 degrees Celsius

注意:我省略了 table,但列表的输入顺序是正确的) 这是我目前所拥有的:

#variable used to set the selected month (should be index value)
month_index = input("Choose the index value of the month you would like to look at:")

#Lists containing data
month = ["January", "Febuary", "March", "April", "May", "June", "July", "August",
         "September", "October", "November", "December"]
avg_temp = [4.6, 6.1, 10.0, 17.0, 23.0, 27.0, 30.0, 29.0, 25.2, 19.0, 12.7, 7.2]

我试过这个有效的语句,但对用户输入无效:

print_statement = (f"The average temperature in New York in {month[2]} "
                   f"is {avg_temp[2]} degrees Celsius")

我还认为可能需要压缩列表来连接两列中的值,如下所示:

month_index = sorted(zip(month, avg_temp)

我搞砸了代码,无法准确记住我写的内容,但基本上结果输出是:

The average temperature in New York in (December, 7.2)

请注意,我不得不在末尾省略 "is x degrees Celsius",这不是一个干净的句子。

您需要先将输入转换为整数,然后在打印语句中使用它,如下所示:

#variable used to set the selected month (should be index value)
month_index = int(input("Choose the index value of the month you would like to look at:"))

#Lists containing data
month = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
avg_temp = [4.6, 6.1, 10.0, 17.0, 23.0, 27.0, 30.0, 29.0, 25.2, 19.0, 12.7, 7.2]

print(f"The average temperature in New York in {month[month_index]} is {avg_temp[month_index]} degrees Celsius")

或者,您可以使用字典,并询问月份名称而不是索引:

#variable used to set the selected month (should be index value)
month_input = input("Choose the month you would like to look at: ")

# List containing data
month = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
avg_temp = [4.6, 6.1, 10.0, 17.0, 23.0, 27.0, 30.0, 29.0, 25.2, 19.0, 12.7, 7.2]

# Converting to a dict
temp_per_month = {month[i]:avg_temp[i] for i in range(len(month))}

print(f"The average temperature in New York in {month_input} is {temp_per_month[month_input]} degrees Celsius")

最后,如果你愿意,你可以压缩,但这里不要排序,因为这将按字母顺序对条目进行排序(所以八月在第一,九月在最后,而不是一月在第一,十二月在最后)。

#variable used to set the selected month (should be index value)
month_index = int(input("Choose the index value of the month you would like to look at:"))

#Lists containing data
month = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
avg_temp = [4.6, 6.1, 10.0, 17.0, 23.0, 27.0, 30.0, 29.0, 25.2, 19.0, 12.7, 7.2]

month_temps = zip(month, avg_temp)

print(f"The average temperature in New York in {month_temps[month_index][0]} is {month_temps[month_index][1]} degrees Celsius")

您提到“我试过这个有效的语句,但没有用户输入”。 在将 user-input 用作列表索引之前,您是否将其转换为整数?

基本上,试试这个:

month_index = int(input("Choose the index value of the month you would like to look at:"))