You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何根据属性值列表筛选字典列表中的元素?

更高效筛选指定ID的人员字典方案

给定人员信息字典列表和目标ID列表,需要筛选出ID匹配的字典组成新列表。已知循环方法可行,以下是两种更优的Python实现方案:

原始数据

list_of_persons = [
    {"id": 2, "name": "name_2", "age": 23},
    {"id": 3, "name": "name_3", "age": 43},
    {"id": 4, "name": "name_4", "age": 35},
    {"id": 5, "name": "name_5", "age": 59}
]

ids_search_list = [2, 4]

方案1:列表推导式

用Python原生的列表推导式实现,写法简洁,性能与循环相当但代码更紧凑:

result_list = [person for person in list_of_persons if person["id"] in ids_search_list]

方案2:集合优化查找(大数据量场景首选)

当ids_search_list包含大量元素时,列表的in操作时间复杂度为O(n),将其转换为集合后,in操作的时间复杂度降至O(1),能大幅提升筛选效率:

# 先将目标ID列表转为集合
ids_search_set = set(ids_search_list)
# 再进行筛选
result_list = [person for person in list_of_persons if person["id"] in ids_search_set]

预期结果

result_list = [
    {"id": 2, "name": "name_2", "age": 23},
    {"id": 4, "name": "name_4", "age": 35}
]

内容的提问来源于stack exchange,提问作者Sipan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:01:04