蝴蝶不菲
您可以使用字典理解:itertools.groupbyfrom itertools import groupbyfrom 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 个带有集合的循环:forfrom collections import defaultdictoutput = {}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}}
慕标5832272
请尝试以下操作: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)