2 回答
TA贡献1810条经验 获得超4个赞
您可以使用字典理解:itertools.groupby
from itertools import groupby
from statistics import median
{k : {y : median((e[1] for e in g)) for y, g in groupby(v, key=lambda x: x[0])} for k, v in dictionary.items()}
输出:
{1: {2019: 29.4, 2020: 28.6}, 2: {2018: 28.2, 2019: 29.8}}
上述解决方案有效,因为您的数据是按年份排序的
或者你可以使用 2 个带有集合的循环:for
from collections import defaultdict
output = {}
for k, v in dictionary.items():
year_value = defaultdict(list)
for y, val in v:
year_value[y].append(val)
output[k] = {y: median(v) for y, v in year_value.items()}
print(output)
输出:
{1: {2019: 29.4, 2020: 28.6}, 2: {2018: 28.2, 2019: 29.8}}
TA贡献1966条经验 获得超4个赞
请尝试以下操作:
dictionary = {1: [[2019, 28.7], [2019, 29.4], [2019, 29.7], [2020, 28.6], [2020, 28.7], [2020, 28.0]],
2: [[2018, 26.9], [2018, 28.2], [2018, 28.5], [2019, 29.9], [2019, 29.8], [2019, 28.7]]}
output = {}
for obj in dictionary.keys():
temp = {}
for i in dictionary[obj]:
if i[0] not in temp:
temp[i[0]] = [i[1]]
else:
temp[i[0]].append(i[1])
output[obj] = temp
for i in output.keys():
for j in output[i].keys():
output[i][j].sort()
n = len(output[i][j])
if n % 2 == 0:
median_1 = output[i][j][n // 2]
median_2 = output[i][j][n // 2 - 1]
median = (median_1 + median_2) // 2
else:
median = output[i][j][n // 2]
output[i][j] = median
print(output)
添加回答
举报