Python如何从字符串键字典中提取最大informationGain对应阈值键值对
通用实现方案
直接用Python内置的max()函数结合自定义key规则就能实现,无需额外引入第三方库,具体操作如下:
实现思路
- 先筛选字典中所有以
informationGain_开头的键,按对应值大小取最大值,提取该键对应的数字索引 - 用拿到的索引拼接出
threshold_开头的键,直接从原字典取出对应阈值即可
完整可运行代码示例
def get_max_gain_threshold(info_dict): # 筛选所有信息增益对应的键 gain_keys = [k for k in info_dict.keys() if k.startswith('informationGain_')] # 找到值最大的信息增益键 max_gain_key = max(gain_keys, key=lambda k: info_dict[k]) # 提取对应索引 idx = max_gain_key.split('_')[-1] # 拼接出对应阈值的键 threshold_key = f'threshold_{idx}' # 返回结构化结果 return { 'max_information_gain': info_dict[max_gain_key], 'corresponding_threshold': info_dict[threshold_key], 'index': int(idx) } # 用示例字典测试 test_dict = {'informationGain_0': 0.9949486404805016, 'threshold_0': 5.0, 'informationGain_1': 0.9757921620455572, 'threshold_1': 12.5, 'informationGain_2': 0.7272727272727273, 'threshold_2': 11.5, 'informationGain_3': 0.5509775004326937, 'threshold_3': 8.6, 'informationGain_4': 0.9838614413637048, 'threshold_4': 7.0, 'informationGain_5': 0.9512050593046015, 'threshold_5': 6.0, 'informationGain_6': 0.8013772106338303, 'threshold_6': 5.9, 'informationGain_7': 0.9182958340544896, 'threshold_7': 1.5, 'informationGain_8': 0.0, 'threshold_8': 9.0, 'informationGain_9': 0.6887218755408672, 'threshold_9': 7.8, 'informationGain_10': 0.9182958340544896, 'threshold_10': 2.1, 'informationGain_11': 0.0, 'threshold_11': 13.5} print(get_max_gain_threshold(test_dict))
运行输出
{'max_information_gain': 0.9949486404805016, 'corresponding_threshold': 5.0, 'index': 0}
优化建议
如果可以修改原有生成字典的代码,更推荐直接用索引作为键存储结构化数据,后续检索效率更高:
# 替换原有entropy_discretization函数里的I更新逻辑 I[i] = { 'informationGain': informationGain, 'threshold': threshold } # 后续查找最大值仅需一行代码 max_item = max(I.values(), key=lambda x: x['informationGain'])
内容的提问来源于stack exchange,提问作者Evan Gertis
相关产品推荐
相关产品推荐

