我正在try 解析一个文件,该文件对其包含的数据具有嵌套 struct .数字嵌套的深度是任意的,每个嵌套都由一个字符串分隔,例如‘Begin’和‘End’.我想构造一个列表(或词典等)来保留文件中数据 struct 的嵌套.

作为一个简单的例子,从一个类似如下的列表中:

input = [0, 'begin', 1, 2, 'begin', 3, 4, 'end', 5, 'end', 6]

我想了解以下内容:

[0, [1, 2, [3, 4], 5], 6]

我try 创建一个递归函数来执行此操作,但无法获得正确的输出.(我会包括我对解决方案的try ,但由于递归,我不知道我是接近还是根本不接近).这个问题该如何解决呢?

编辑以添加我的try (我希望这不会只是混淆):

input = [0, 'begin', 1, 2, 'begin', 3, 4, 'end', 5, 'end', 6]

def create_nest(items, nest):
    for i, item in enumerate(items):
        if item == 'begin':
            nest.append(create_nest(items[i+1:], []))
        elif item == 'end':
            return nest
        else:
            nest.append(item)

nested_list = []
create_nest(input, nested_list)

这会产生以下结果:

[0, [1, 2, [3, 4], 3, 4], 1, 2, [3, 4], 3, 4]

推荐答案

使用递归函数、迭代器来避免跟踪当前项,并利用列表的易变性:

def to_nested(inpt, out=None):
    it = iter(inpt)   # use an iterator
    if out is None: # optional: just to avoid using a list as default
        out = []    #
    for item in it:
        if item == 'begin': # if begin, let's start a new level
            out.append([])  # add a new list and pass this recursively
            to_nested(it, out=out[-1])
        elif item == 'end': # if end, let's finish this recursion
            return
        else:               # else, add an item to the current level
            out.append(item)
    return out

to_nested([0, 'begin', 1, 2, 'begin', 3, 4, 'end', 5, 'end', 6])
# [0, [1, 2, [3, 4], 5], 6]

Note that this assumes a correct format (as many ends as there are begins). If not, you would have to keep track of them.

modification of your approach using an iterator like I did

inpt = [0, 'begin', 1, 2, 'begin', 3, 4, 'end', 5, 'end', 6]

def create_nest(items, nest):
    items = iter(items)
    for item in items:
        if item == 'begin':
            nest.append(create_nest(items, []))
        elif item == 'end':
            return nest
        else:
            nest.append(item)
    return nest

nested_list = []
create_nest(inpt, nested_list)
# [0, [1, 2, [3, 4], 5], 6]

Python相关问答推荐

如果在第一行之前不存在其他条件,如何获得满足口罩条件的第一行?

不同数据类型的Python成员变量不会在具有相同优先级的不同线程中更新

有什么方法可以修复奇怪的y轴Python matplotlib图吗?

Django注释:将时差转换为小数或小数

使用argsorted索引子集索引数组

比较两个二元组列表,NP.isin

将numpy数组存储在原始二进制文件中

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

使用新的类型语法正确注释ParamSecdecorator (3.12)

Python 约束无法解决n皇后之谜

沿着数组中的轴计算真实条目

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

在Python中管理打开对话框

如何从数据库上传数据到html?

CommandeError:模块numba没有属性generated_jit''''

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

将标签移动到matplotlib饼图中楔形块的开始处

如何找出Pandas 图中的连续空值(NaN)?

从旋转的DF查询非NaN值