简体   繁体   English

如何聚合每日温度数据以使用月份作为python字典中的键?

[英]How to aggregate daily temperature data to use the months as keys in a dictionary for python?

I am a novice with python so forgive me if this seems simple and I can't figure it out...我是python的新手,所以如果这看起来很简单而且我无法弄清楚,请原谅我......

For a homework assignment we are asked to "Write python code to read the daily temperature data for each month of the year. Make three dictionaries, MinT , AvgT , and MaxT each with the month number (1..12) as the key and a list of values for the minimum, maximum and average daily temperatures for each day in the corresponding month."对于家庭作业,我们被要求“编写 python 代码以读取一年中每个月的每日温度数据。制作三个字典MinTAvgTMaxT每个字典都以月份编号 (1..12) 为关键字,并且相应月份中每一天的最低、最高和平均每日温度值的列表。” I need to do this without using pandas and numpy, as those are the next questions for the assignment.我需要在不使用 pandas 和 numpy 的情况下执行此操作,因为这些是作业的下一个问题。

I am struggling to get started.我正在努力开始。 I am trying to start with MinT to see if I could get the code to work, but have failed multiple times.我正在尝试从MinT开始,看看我是否能让代码正常工作,但多次失败。 So far I have...到目前为止我有...

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']))

The output is all of the minimum values for the year, but I'm unsure how to aggregate the daily data to where I can use the month as the key.输出是当年的所有最小值,但我不确定如何将每日数据聚合到可以使用月份作为关键的位置。

Any help would be appreciated.任何帮助,将不胜感激。

To create a dictionary where they keys are the numeric months and the values will be lists, you want:要创建一个字典,其中键是数字月份,值是列表,您需要:

MinT = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], 11:[], 12:[]}

However this is easier to initialize with a loop:但是,使用循环更容易初始化:

MinT = {}
for x in range(12):
 MinT[x+1] = []

Or dictionary comprehension:或字典理解:

MinT = {month_num + 1: [] for month_num in range(12)}

Here's a self contained example using comprehensions :这是一个使用理解的自包含示例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM