如何根据阈值从字典列表中筛选符合条件的字典组成新列表
筛选字典列表中符合score阈值的元素
原代码问题
你的代码存在几个明显问题:
- 键名大小写不匹配:原字典里的名字键是
'Name',但你写的是'name',会触发KeyError - 多余的内层循环:遍历
list_dict[i]['name']是在逐个取名字的字符,完全没必要,我们要处理的是整个字典元素 - 未正确构建结果:你只是打印字符,没有把符合条件的字典加入结果列表,无法得到预期的字典列表
正确实现方法
方法1:常规循环实现
直接遍历每个字典元素,判断score是否超过阈值,符合条件就加入结果列表:
list_dict = [{'Name': 'Andres', 'score': 0.17669814825057983}, {'Name': 'Paul', 'score': 0.14028045535087585}, {'Name': 'Feder', 'score': 0.1379694938659668}, {'Name': 'James', 'score': 0.1348174512386322}] threshold = 0.15 result = [] for item in list_dict: if item['score'] > threshold: # 如果需要把键名'Name'改成小写'name',用下面这行替换append(item) # result.append({'name': item['Name'], 'score': item['score']}) result.append(item) print(result)
输出:
[{'Name': 'Andres', 'score': 0.17669814825057983}]
方法2:列表推导式(更简洁)
用Python列表推导式可以一行完成筛选,代码更紧凑:
list_dict = [{'Name': 'Andres', 'score': 0.17669814825057983}, {'Name': 'Paul', 'score': 0.14028045535087585}, {'Name': 'Feder', 'score': 0.1379694938659668}, {'Name': 'James', 'score': 0.1348174512386322}] threshold = 0.15 # 直接筛选原结构的字典 result = [item for item in list_dict if item['score'] > threshold] # 如果要改成小写'name'键名 result = [{'name': item['Name'], 'score': item['score']} for item in list_dict if item['score'] > threshold] print(result)
输出和预期完全一致:
[{'name': 'Andres', 'score': 0.17669814825057983}]
内容的提问来源于stack exchange,提问作者math_guy_shy
相关产品推荐
相关产品推荐

