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

Python遍历字典保留含指定House编号字符串键的实现方案

问题原因

原代码的判断逻辑存在错误:内层遍历house_list时,只要当前key不包含某一个house_id对应的House字符串就会触发删除,导致原本匹配House1的key会因为不匹配House2被误删。

正确实现

方案1:字典推导式(推荐,简洁易读)

直接生成符合要求的新字典:

input_list = {"This_is_House1_Test1": "one", "Also_House2_Mother": "two", "Fefe_House3_Father": "three"}
house_list = [1, 2]

res = {k: v for k, v in input_list.items() if any(f"House{hid}" in k for hid in house_list)}

输出结果即为预期:{"This_is_House1_Test1": "one", "Also_House2_Mother": "two"}

方案2:原地修改原字典

如果需要直接修改原字典对象,调整判断逻辑即可:

input_list = {"This_is_House1_Test1": "one", "Also_House2_Mother": "two", "Fefe_House3_Father": "three"}
house_list = [1, 2]

for key in list(input_list.keys()):
    if not any(f"House{hid}" in key for hid in house_list):
        input_list.pop(key)

内容的提问来源于stack exchange,提问作者Avión

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:45:03