First we read in the data:
days = []
temperatures = []
for line in open('data/munich_temperatures_average.txt', 'r'):
day, temperature = line.strip().split()
# day and temperature are strings so we need to convert them
# when we append them to the lists
days.append(float(day))
temperatures.append(float(temperature))
Now that the data has been read into two lists, we can loop through and split up the temperatures by year:
yearly_temperatures = {}
for i in range(len(days)):
# Find the year (as an integer)
year = int(days[i])
# If the key doesn't exist in the dictionary, create it
if not year in yearly_temperatures:
yearly_temperatures[year] = []
# Add the temperature to the list
yearly_temperatures[year].append(temperatures[i])
Having done this, the dictionary contains for each year a list of average temperatures. We can now loop through the years and find the minimum, average, and maximum:
for year in yearly_temperatures:
# We can store the current temperature list in a variable
# to avoid having to write it out every time.
t_list = yearly_temperatures[year]
print(year, min(t_list), sum(t_list) / len(t_list), max(t_list))
In this case, the dates are in the right order, but when looping over a dictionary, order is not guaranteed, so it is safer to do:
for year in sorted(yearly_temperatures.keys()):
t_list = yearly_temperatures[year]
print(year, min(t_list), sum(t_list) / len(t_list), max(t_list))
Now we can try and do the same thing, but sorting by month instead of year. For simplicity, let's assume that all 12 months are the same length:
monthly_temperatures = {}
for i in range(len(days)):
# Find the month (as an integer). This finds the fractional
# part of the date, multiplies it by 12, and then converts
# to an integer. We then have to add 1 to make sure it is in
# the range 1-12 (not 0-11).
month = int(12. * (days[i] - int(days[i]))) + 1
# If the key doesn't exist in the dictionary, create it
if not month in monthly_temperatures:
monthly_temperatures[month] = []
# Add the temperature to the list
monthly_temperatures[month].append(temperatures[i])
for month in sorted(monthly_temperatures.keys()):
m_list = monthly_temperatures[month]
print(month, min(m_list), sum(m_list) / len(m_list), max(m_list))
If we want to show the month, we can use a dictionary:
MONTHS = {}
MONTHS[1] = "January"
MONTHS[2] = "February"
MONTHS[3] = "March"
MONTHS[4] = "April"
MONTHS[5] = "May"
MONTHS[6] = "June"
MONTHS[7] = "July"
MONTHS[8] = "August"
MONTHS[9] = "September"
MONTHS[10] = "October"
MONTHS[11] = "November"
MONTHS[12] = "December"
for month in sorted(monthly_temperatures.keys()):
m_list = monthly_temperatures[month]
print(MONTHS[month], min(m_list), sum(m_list) / len(m_list), max(m_list))