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

Python 3.x:将嵌套列表转换为带最大递归的嵌套字典

嵌套列表转嵌套字典(递归实现)

需求说明

将特定格式的嵌套列表转换为对应的嵌套字典,要求采用递归方式实现。

输入示例:

["Pie", ["Sugar", "Biscuit", ["Egg"] ], "Cocoa", []]

对应输出:

{ "Pie": { "Sugar": {}, "Biscuit": { "Egg": {} } }, "Cocoa": {} }

输入规则说明

符合要求的输入需遵循:顶级元素为字符串或列表,且字符串后可跟随一个列表作为其对应的值;列表内部的结构同理。


符合要求的嵌套列表示例

  • 示例1:
["Pie", ["Sugar", "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]
  • 示例2:
["Pie", ["Sugar", ["Biscuit"], "Another something", ["Egg"], "Something", ["Something2"] ], "Cocoa", ["One", ["Nested1"], "Two", ["Nested2"] ]]

不符合要求的嵌套列表示例

  • 示例1:字符串被嵌套在列表中作为直接子元素(如[["Sugar"]])
["Pie", [["Sugar"], "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]
  • 示例2:顶级元素为嵌套列表(如[["Pie"]])
[["Pie"], ["Sugar", "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]

递归实现代码

def list_to_dict(lst):
    result = {}
    i = 0
    while i < len(lst):
        # 处理字符串键
        if isinstance(lst[i], str):
            key = lst[i]
            # 检查下一个元素是否为列表,作为当前键的值
            if i + 1 < len(lst) and isinstance(lst[i+1], list):
                result[key] = list_to_dict(lst[i+1])
                i += 2  # 跳过已处理的列表值
            else:
                result[key] = {}
                i += 1
        # 处理列表元素(递归解析内部结构)
        elif isinstance(lst[i], list):
            result.update(list_to_dict(lst[i]))
            i += 1
    return result

测试验证

# 测试第一个示例输入
test_input = ["Pie", ["Sugar", "Biscuit", ["Egg"] ], "Cocoa", []]
print(list_to_dict(test_input))
# 输出: {'Pie': {'Sugar': {}, 'Biscuit': {'Egg': {}}}, 'Cocoa': {}}

代码逻辑说明

  1. 遍历输入列表,使用while循环控制索引,以便处理键值对时跳过对应的列表元素
  2. 遇到字符串时,将其作为字典的键:
    • 若下一个元素是列表,递归调用函数处理该列表作为键的值,索引加2
    • 否则键对应的值为空字典,索引加1
  3. 遇到列表时,递归解析该列表的结构,并将结果合并到当前字典(空列表会返回空字典,不影响最终结果)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:04:04