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

如何快速将点分隔字符串列表转换为对应层级结构的YAML?

实现方案

这里以Python为例,给出一个高效的实现方式,时间复杂度为O(L),L是所有字符串的字符总长度,不管路径层级多少都能快速适配:

步骤说明

  1. 先把所有点分隔的字符串拆解为路径片段,用前缀树存储层级关系
  2. 把前缀树转换为符合要求的嵌套结构
  3. 直接输出为YAML格式

依赖安装

需要先安装PyYAML处理YAML输出:

pip install pyyaml

可运行代码

import yaml
from collections import defaultdict

# 递归默认字典,自动创建不存在的节点,不用手动判断
def nested_defaultdict():
    return defaultdict(nested_defaultdict)

# 把前缀树转换为要求的输出结构
def tree_to_format(node):
    res = []
    for key, child in node.items():
        child_content = tree_to_format(child)
        # 子节点为空说明当前key是末端值,直接加入列表
        if not child_content:
            res.append(int(key) if key.isdigit() else key)
        # 有子节点则包装为单键字典
        else:
            res.append({key: child_content})
    return res

if __name__ == "__main__":
    strings = ["foo.bar.1", "foo.bar.2", "foo.bar.A.1", "foo.bar.A.2"]
    # 构建前缀树
    root = nested_defaultdict()
    for s in strings:
        current = root
        for part in s.split("."):
            current = current[part]
    # 转换结构并输出YAML
    output = tree_to_format(root)[0]
    print(yaml.dump(output, sort_keys=False, indent=2, allow_unicode=True))

输出结果

运行代码后会直接得到你需要的YAML:

foo:
  - bar:
    - 1
    - 2
    - A:
      - 1
      - 2

如果不想引入第三方依赖,也可以自己写递归打印函数生成YAML,逻辑和上面的tree_to_format类似,遇到字典就加缩进和冒号,遇到列表就加-前缀即可,实现起来也很简单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:54:04