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

如何将可变大小的数组转换为嵌套Python列表?

问题描述

给定一个大小可变的二维数组(示例为4×4):

my_array = [[A11, A12, A13, A14],
            [A21, A22, A23, A24],
            [A31, A32, A33, A34],
            [A41, A42, A43, A44]]

需要将其转换为嵌套的列表与字典结构,满足以下要求:

  • 同一列的相同元素归到同一个分组中
  • 数组的最后一个有效元素(非None)需存入列表
  • 忽略所有末尾的None值

示例输入输出:

sample_array = [[AA, BB, CC, DD],
                [AA, BB, PP, None],
                [AA, BB, QQ, RR],
                [AA, BB, QQ, SS],
                [AA, JJ, UU, None],
                [EE, FF, TT, None]]
                
output = [{AA:[ 
              {BB:[ 
                   {CC:[DD]}, 
                   [PP], 
                   {QQ:[RR,SS]} 
                   ]}, 
               {JJ:[UU]} 
              ]}, 
          {EE:[ 
              {FF:[TT]} 
              ]}]
解决方案

可以通过字典树(Trie)+ 递归转换的方式处理任意维度的数组,核心逻辑是先构建路径层级关系,再将其转换为要求的嵌套结构。

实现代码

def transform_array(arr):
    # 预处理行:去掉末尾的None,保留有效路径
    def preprocess_row(row):
        trimmed = []
        for elem in row:
            if elem is None:
                break
            trimmed.append(elem)
        return trimmed if trimmed else None

    valid_paths = [path for path in map(preprocess_row, arr) if path]
    if not valid_paths:
        return []

    # 定义字典树节点
    class TrieNode:
        def __init__(self):
            self.children = {}
            self.values = []  # 存储路径末尾的元素

    # 构建字典树
    root = TrieNode()
    for path in valid_paths:
        node = root
        for idx, elem in enumerate(path):
            if idx == len(path) - 1:
                node.values.append(elem)
            else:
                if elem not in node.children:
                    node.children[elem] = TrieNode()
                node = node.children[elem]

    # 将字典树转换为目标结构
    def trie_to_structure(node):
        result = []
        # 处理中间节点(转换为字典)
        for key, child_node in node.children.items():
            result.append({key: trie_to_structure(child_node)})
        # 处理末尾元素(转换为列表)
        if node.values:
            result.append(node.values)
        return result

    # 生成最终结果
    final_result = []
    for key, child_node in root.children.items():
        final_result.append({key: trie_to_structure(child_node)})
    
    return final_result

测试示例

# 定义示例变量
AA, BB, CC, DD = "AA", "BB", "CC", "DD"
PP, QQ, RR, SS = "PP", "QQ", "RR", "SS"
JJ, UU = "JJ", "UU"
EE, FF, TT = "EE", "FF", "TT"

sample_array = [[AA, BB, CC, DD],
                [AA, BB, PP, None],
                [AA, BB, QQ, RR],
                [AA, BB, QQ, SS],
                [AA, JJ, UU, None],
                [EE, FF, TT, None]]

print(transform_array(sample_array))

输出结果与示例完全一致:

[
    {'AA': [
        {'BB': [{'CC': ['DD']}, ['PP'], {'QQ': ['RR', 'SS']}]},
        {'JJ': ['UU']}
    ]},
    {'EE': [{'FF': ['TT']}]}
]

逻辑说明

  1. 预处理行:过滤每一行末尾的None,得到有效路径,避免无效值干扰结构。
  2. 字典树构建:将所有有效路径存入字典树,中间元素作为树的节点,末尾元素存入节点的values列表,自动完成相同前缀的分组。
  3. 递归转换结构:遍历字典树,将中间节点转换为嵌套字典,末尾元素转换为列表,最终组合成要求的格式。

这种方法可以自动适配任意维度的输入数组,完全满足分组和忽略None的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:50:39