[英]How to aggregate daily temperature data to use the months as keys in a dictionary for python?
我是python的新手,所以如果這看起來很簡單而且我無法弄清楚,請原諒我......
對於家庭作業,我們被要求“編寫 python 代碼以讀取一年中每個月的每日溫度數據。制作三個字典MinT
、 AvgT
和MaxT
每個字典都以月份編號 (1..12) 為關鍵字,並且相應月份中每一天的最低、最高和平均每日溫度值的列表。” 我需要在不使用 pandas 和 numpy 的情況下執行此操作,因為這些是作業的下一個問題。
我正在努力開始。 我正在嘗試從MinT
開始,看看我是否能讓代碼正常工作,但多次失敗。 到目前為止我有...
import csv
weather = csv.DictReader(open(...))
MinT = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
min_t = []
for r in weather:
min_t.append(float(r['LowT']))
輸出是當年的所有最小值,但我不確定如何將每日數據聚合到可以使用月份作為關鍵的位置。
任何幫助,將不勝感激。
要創建一個字典,其中鍵是數字月份,值是列表,您需要:
MinT = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], 11:[], 12:[]}
但是,使用循環更容易初始化:
MinT = {}
for x in range(12):
MinT[x+1] = []
或字典理解:
MinT = {month_num + 1: [] for month_num in range(12)}
這是一個使用理解的自包含示例:
from random import randint
def generate_temperatures():
return [randint(60, 92) for day in range(randint(28, 31))]
# This simulates loading your data
annual_temperatures = {month_num + 1: generate_temperatures() for month_num in range(12)}
# This calculates the goods :)
avg_monthly_temperature = {month: sum(temp)/len(temp) for (month, temp) in annual_temperatures.items()}
min_monthly_temperature = {month: min(temp) for (month, temp) in annual_temperatures.items()}
max_monthly_temperature = {month: max(temp) for (month, temp) in annual_temperatures.items()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.