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

Python无需导入库如何校验嵌套飞船字典中是否存在指定内鬼

实现方案

核心思路

通过递归遍历多层嵌套字典结构,不需要引入任何外部依赖:每次遍历当前层级的所有键值对,遇到crews键就直接检查目标内鬼是否在对应的数组中,找到就直接返回存在;如果值是字典类型,说明是下层嵌套房间,递归进入继续查找,所有层级遍历完成都没找到则返回不存在。

完整实现代码

def check_impostor(current_room, impostor):
    for key, value in current_room.items():
        # 遇到crews数组直接校验内鬼是否存在
        if key == "crews":
            if impostor in value:
                return True
        # 遇到嵌套的房间字典递归查找
        elif isinstance(value, dict):
            if check_impostor(value, impostor):
                return True
    # 所有层级遍历完毕未找到
    return False

测试用例验证

测试用例1

spaceship1 = {
    "cafeteria": {
        "weapons": {
            "o2": {
                "communications": {
                    "storage": {
                        "crews": ["super_saiyanXD"]
                    }
                }
            }
        },
        "crews": ["someotherguy"]
    }
}
impostor1 = "xXimanimpostor9999Xx"
print(check_impostor(spaceship1, impostor1)) # 输出False

测试用例2

spaceship2 = {
    "cafeteria": {
        "storage": {
            "crews": ["iamnottheimpostor"]
        },
        "crews": [] # 该房间为空
    },
    "shields": {
        "crews": ["piwdipi", "davie214", "toasted_guy_45"],
        "weapons": {
            "crews": ["xXimanimpostor9999Xx"] # 内鬼在该房间内
        }
    }
}
impostor2 = "toasted_guy_45"
print(check_impostor(spaceship2, impostor2)) # 输出True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 02:54:03