Skip to main content
 首页 » 编程设计

python之在使用 Python 迭代创建的嵌套列表中选择上面的级别

2024年10月01日9unruledboy

我在列表中搜索了很多问题,但找不到我要找的东西。

我有一个用大括号包裹一些值的字符串和一些包含值的其他嵌套大括号对。我不知道结构嵌套的最深层次,但它可能看起来像这样:

{121{12}12{211}2}

我想遍历这个字符串并以类似于以下伪代码的方式将它传输到嵌套列表:

for i in thestring 
if there is a leftbrace { start a new list inside the current list 
elseif there is a rightbrace } close the current list and select the list on the level above 
else add i to currently selected list 

我不知道如何提升列表级别并关闭当前子列表

请您参考如下方法:

def listify(s): 
    i = iter(s) 
    l = [] 
    for c in i: 
        if c == '{': 
            l.append(listify(i)) 
        elif c == '}': 
            return l 
        else: 
            l.append(c) 
    return l[0] 

诀窍是使用递归函数,以便堆栈负责跟踪您所在的列表。我们使用 iter 以便我们可以将字符串传递给递归调用而无需字母我们已经处理过了。

>>>listify(s) 
['1', '2', '1', ['1', '2'], '1', '2', ['2', '1', '1'], '2']