Python 特定的字典平均值



我有字典:

{201001: '-28.3', 201002: '-23.8', 201003: '-24.2', 201004: '-14.1',
201005: '-7.5', 201006: '0.1', 201007: '5.0', 201008: '5.6',
201009: '2.6', 201010: '-5.0', 201011: '-12.1', 201012: '-23.6',
201101: '-23.0', 201102: '-21.7', 201103: '-21.9', 201104: '-19.5',
201105: '-6.0', 201106: '0.7', 201107: '4.8', 201108: '5.2',
201109: '2.3', 201110: '-4.9', 201111: '-18.5', 201112: '-23.8'}

这本字典表示阿拉斯加的温度。201001: '-28.3'表示阿拉斯加在 2010 年 1 月的温度是 -28.3 摄氏度。

我想逐年获得冬季的平均温度,即

( January’s + February’s ) / 2.

例如 2010 年的冬季平均气温为(-28.3 + -23.8) / 2.

我认为逐年查看和直接输入平均值并不优雅,因为 2000~2019 年还有更多年份。

(为了可读性,我只输入了 2 年 2010,2011。 如何在字典中逐年获取特定数据的平均值?

温度 按年份

by_year = {}
for k, v in d.items():
# k // 100 is year
by_year.setdefault(k //100, []).append(float(v))

冬季平均气温

avg_winter = {}
for k, months in by_year.items():
# months[:2] to average first two months
avg_winter[k] = sum(months[:2])/len(months[:2])

输出

from pprint import pprint
pprint(by_year)
pprint(avg_winter)
by_year
{2010: [-28.3,
-23.8,
-24.2,
-14.1,
-7.5,
0.1,
5.0,
5.6,
2.6,
-5.0,
-12.1,
-23.6],
2011: [-23.0,
-21.7,
-21.9,
-19.5,
-6.0,
0.7,
4.8,
5.2,
2.3,
-4.9,
-18.5,
-23.8]}
avg_winter
{2010: -26.05, 2011: -22.35}

只需一个简单的循环就可以了,不是吗?

from typing import Dict
def avg_winter_temps(temps: Dict[int, float]) -> Dict[int, float]:
winter_temps = {}
for year in range(2010, 2019+1):
jan, feb = year*100 + 1, year*100 + 2
winter_temps[year] = (temps[jan] + temps[feb])/2
return winter_temps

您可以使用正则表达式查找以"01"或"02"结尾的键:


import re
dictionary = {201001: '-28.3', 201002: '-23.8', 201003: '-24.2', 201004: '-14.1',
201005: '-7.5', 201006: '0.1', 201007: '5.0', 201008: '5.6',
201009: '2.6', 201010: '-5.0', 201011: '-12.1', 201012: '-23.6',
201101: '-23.0', 201102: '-21.7', 201103: '-21.9', 201104: '-19.5',
201105: '-6.0', 201106: '0.7', 201107: '4.8', 201108: '5.2',
201109: '2.3', 201110: '-4.9', 201111: '-18.5', 201112: '-23.8'}
key_list = dictionary.keys()
months = 0
sum = 0
averages = []
for key in key_list:
match = re.search("01$|02$", str(key)) # String ends in '01; or in '02'
if match:
if months == 0:
sum += float(dictionary.get(key))
months += 1
else:
sum += float(dictionary.get(key))
months = 0
averages.append(sum / 2)
sum = 0
print(averages)

输出:

[-26.05, -22.35]

这不是对所提问题的答案,而是补充现有答案,如果你想考虑到要计算一月至二月期间的平均温度,月平均值应该按相关月份的长度加权。 函数calc_jan_feb_average可用于计算此加权平均值。 由于闰年,它需要年份作为输入参数。

import datetime
def get_length_feb(year):
return (datetime.datetime(year, 3, 1)
- datetime.datetime(year, 2, 1)).total_seconds()
def calc_jan_feb_average(year, jan_temp, feb_temp):
length_jan = 31 * 86400
length_feb = get_length_feb(year)
return (
((jan_temp * length_jan) + (feb_temp * length_feb)) /
(length_jan + length_feb)
)

这是你要找的吗?

temps = {201001: '-28.3', 201002: '-23.8', 201003: '-24.2', 201004: '-14.1',
201005: '-7.5', 201006: '0.1', 201007: '5.0', 201008: '5.6',
201009: '2.6', 201010: '-5.0', 201011: '-12.1', 201012: '-23.6',
201101: '-23.0', 201102: '-21.7', 201103: '-21.9', 201104: '-19.5',
201105: '-6.0', 201106: '0.7', 201107: '4.8', 201108: '5.2',
201109: '2.3', 201110: '-4.9', 201111: '-18.5', 201112: '-23.8'}
avgs = {}
jan = min(temps.keys()) // 100 * 100 + 1
limit = max(temps.keys())
while jan <= limit:
jt = temps.get(jan)
feb = jan + 1
ft = temps.get(feb)
if jt is not None and ft is not None:
avgs[f'{jan} - {feb}'] = (float(jt) + float(ft)) / 2
jan += 100
for period, avg in avgs.items():
print(f'{period} = {avg}')

输出:

201001 - 201002 = -26.05
201101 - 201102 = -22.35

最新更新