Python函数实现字典数据阈值频次统计报错求助
问题分析与解决
错误原因
threshold是temp_freq函数内部的局部变量,函数外部的print语句无法访问,导致NameError。temp_freq函数定义时没有参数,但调用时传入了exceedances,而exceedances同样是函数内部的局部变量,外部也无法访问,属于无效传参。- 原函数仅能处理
temperature指标,不符合需求中“计算给定字典中各指标超过指定阈值的频次”的要求。
修正后的单个指标处理代码
observation = {'temperature': [85, 90, 15, 25, 90, 11, 20, 15, 25], 'dewpoint': [80, 85, 10, 20, 85, 8, 15, 15, 22], 'wind speed': [5, 10, 2, 0, 25, 30, 35, 4, 2], 'precipitation': [0, 0, 0, 2, 1, 0, 1, 0, 3]} def calc_exceedance_freq(metric, threshold): exceedances = 0 for value in observation[metric]: if value > threshold: exceedances += 1 return exceedances threshold = 50 count = calc_exceedance_freq('temperature', threshold) print(f"temperature exceeded {threshold} {count} times")
支持所有指标的通用解决方案
如果需要一次性输出所有指标的超限频次,可以遍历字典的键,逐个计算:
observation = {'temperature': [85, 90, 15, 25, 90, 11, 20, 15, 25], 'dewpoint': [80, 85, 10, 20, 85, 8, 15, 15, 22], 'wind speed': [5, 10, 2, 0, 25, 30, 35, 4, 2], 'precipitation': [0, 0, 0, 2, 1, 0, 1, 0, 3]} def calc_exceedance_freq(metric, threshold): exceedances = 0 for value in observation[metric]: if value > threshold: exceedances += 1 return exceedances # 定义各指标对应的阈值(可根据需求调整) thresholds = { 'temperature': 50, 'dewpoint': 60, 'wind speed': 20, 'precipitation': 1 } for metric, threshold in thresholds.items(): count = calc_exceedance_freq(metric, threshold) print(f"{metric} exceeded {threshold} {count} times")
关键改进点
- 将
metric(指标名)和threshold(阈值)作为参数传入函数,避免局部变量无法外部访问的问题。 - 函数职责单一,仅负责计算指定指标的超限频次,复用性更强。
- 通用方案通过遍历字典和阈值映射,实现了所有指标的批量计算,符合需求要求。
内容的提问来源于stack exchange,提问作者user28135631
相关产品推荐
相关产品推荐

