如何按条件从字典列表中获取相同key前缀对应的confidence最大值
问题分析
现有代码仅收集了所有条目的confidence值,缺少分组存储、同组内最大值比较的逻辑,无法得到分组后的最大值。
实现代码
无需引入额外依赖,使用原生Python即可实现:
ab = [{'key': 'gdpr.gdpr_compliance.1', 'value': 'Yes', 'idref': '69dbdba4-14d4-4ac8-a318-0d658e4d5b07', 'xpath': '/html/body/p[24]', 'confidence': 0.985}, {'key': 'gdpr.gdpr_compliance.2', 'value': 'Yes', 'idref': '69e2589a-bbf2-49c3-96fc-01fbee5dde03', 'xpath': '/html/body/p[27]', 'confidence': 0.989}, {'key': 'data_collected.personally_identifiable_information.1', 'value': 'Yes', 'idref': 'f6819b54-07a7-4839-b0cc-8343eed28342', 'xpath': '/html/body/ul[6]/li[1]', 'confidence': 0.562}, {'key': 'data_collected.personally_identifiable_information.2', 'value': 'Yes', 'idref': '496400e5-9665-4697-96bc-c55176cdbd02', 'xpath': '/html/body/ul[6]/li[2]', 'confidence': 0.661}] # 初始化分组存储字典,key为前缀,value为对应分组当前最大confidence值 group_max_conf = {} for item in ab: # 提取key的第一级前缀 prefix = item['key'].split('.')[0] current_conf = item['confidence'] # 前缀未存储时直接赋值,已存储时取更大值更新 if prefix not in group_max_conf or current_conf > group_max_conf[prefix]: group_max_conf[prefix] = current_conf # 将分组最大值转为列表 result = list(group_max_conf.values()) print(result)
输出结果
运行代码后得到预期输出:[0.989, 0.661]
内容的提问来源于stack exchange,提问作者ImMJ
相关产品推荐
相关产品推荐

