我有一個表,其中包含給定的一年月平均溫度,我需要開發一些 python 代碼,允許用戶選擇一個月并將所選月份和相應的月??平均溫度列印到螢屏上,輸出如下所示:
The average temperature in New York in March is 10.0 degrees Celsius
(注意:我省略了表格,但串列以正確的順序輸入)這是我目前所擁有的:
#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"在最后省略了,這不是一個干凈整潔的句子。
uj5u.com熱心網友回復:
您需要先將輸入轉換為整數,然后在列印陳述句中使用它,如下所示:
#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")
最后,您可以根據需要進行壓縮,但此處不要排序,因為這將按字母順序對條目進行排序(因此 8 月將是第一個,9 月最后一個,而不是 1 月第一個和 12 月最后一個)。
#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")
uj5u.com熱心網友回復:
您提到“我嘗試了這個有效的陳述句,但不適用于用戶輸入”。在將用戶輸入用作串列索引之前,您是否將其轉換為整數?
基本上,試試這個:
month_index = int(input("Choose the index value of the month you would like to look at:"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452128.html
