将类路径字符串列表转换为任意深度的嵌套列表字典
类路径字符串转任意深度嵌套列表字典的实现
问题描述
需要将类路径字符串列表转换为支持任意深度的嵌套列表字典结构,示例输入如下:
['/SKA_20-VA-001/SKA_20-V-0546', '/SKA_20-VA-001/SKA_20-V-0148', '/SKA_20-VA-001/SKA_20-LT-0028A/SKA_20-LI-0028A', '/SKA_20-VA-001/SKA_20-LT-0028A/SKA_20-LI-0028B', '/SKA_20-VA-001/SKA_20-PT-0034/SKA_20-PI-0034', '/SKA_20-VA-001/SKA_20-V-0685', '/SKA_20-VA-001/SKA_20-V-0551']
需求是将其转换为嵌套字典存储路径层级,每个父目录作为字典键,对应值为包含子文件/子目录字典的列表,期望结果如下:
{ "SKA_20-VA-001": [ "SKA_20-V-0546", "SKA_20-V-0148", "SKA_20-V-0685", "SKA_20-V-0551", {"SKA_20-LT-0028A": ["SKA_20-LI-0028A", "SKA_20-LI-0028B"]}, {"SKA_20-PT-0034": ["SKA_20-PI-0034"]} ] }
实现方案
通过遍历路径层级、逐步构建嵌套结构的方式实现,以下是Python代码:
def build_nested_structure(paths): root = {} for path in paths: # 分割路径并过滤空字符串(处理开头的/) parts = [p for p in path.split('/') if p] current_level = root # 遍历路径的中间层级(除最后一个节点外) for part in parts[:-1]: # 检查当前层级是否已存在该目录的字典条目 existing_dir = next((item for item in current_level.get(part, []) if isinstance(item, dict) and part in item), None) if not existing_dir: # 不存在则创建新的目录字典并加入列表 new_dir = {part: []} if part not in current_level: current_level[part] = [] current_level[part].append(new_dir) current_level = new_dir[part] else: # 存在则进入该目录的列表层级 current_level = existing_dir[part] # 处理路径的最后一个节点(叶子节点) last_part = parts[-1] if len(parts) == 1: # 根节点直接添加 if last_part not in root: root[last_part] = [] else: if last_part not in root[last_part]: root[last_part].append(last_part) else: # 避免重复添加叶子节点 if last_part not in current_level: current_level.append(last_part) return root
代码说明
- 路径分割:将每个路径按
/拆分,过滤掉开头的空字符串,得到清晰的层级节点列表。 - 层级遍历构建:逐个遍历路径的中间层级,检查当前层级是否已有对应目录的字典条目,没有则创建新条目并进入下一层级;已有则直接进入该目录的列表。
- 叶子节点处理:将路径的最后一个节点添加到对应父目录的列表中,同时避免重复添加。
- 任意深度支持:通过循环遍历所有路径层级,无论路径深度多少都能正确构建嵌套结构。
测试示例:
paths = ['/SKA_20-VA-001/SKA_20-V-0546', '/SKA_20-VA-001/SKA_20-V-0148', '/SKA_20-VA-001/SKA_20-LT-0028A/SKA_20-LI-0028A', '/SKA_20-VA-001/SKA_20-LT-0028A/SKA_20-LI-0028B', '/SKA_20-VA-001/SKA_20-PT-0034/SKA_20-PI-0034', '/SKA_20-VA-001/SKA_20-V-0685', '/SKA_20-VA-001/SKA_20-V-0551'] result = build_nested_structure(paths) import json print(json.dumps(result, indent=2))
运行后会输出符合期望的嵌套结构。
内容的提问来源于stack exchange,提问作者Yoda
相关产品推荐
相关产品推荐

