将字符串转换为嵌套列表

2024-10-02 02:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够打开字符串,例如:'(* (+ int (+ int real)) int)'
放入嵌套的列表中,括号是列表的开始/结束,如下所示(在本例中)

['*', ['+', 'int', ['+', 'int', 'real']], 'int']

我尝试了以下代码,但它不工作

def bracketCheck(el):
if el == ')' or el == '(':
    return False
else:
    return True



def stringIntoList(lst):
lst1 = ''
lst2 = []

for i in range(0, len(lst)-1):
    if bracketCheck(lst[i]):
        lst1 += lst[i]
    elif lst[i] == '(':
        b = stringIntoList(lst[i:])
    elif lst[i] == ')':
        lst2.append(lst1)
        lst2.append(b)
        lst1 = ''
return lst2 

Tags: 字符串列表returnifdefrealelint
1条回答
网友
1楼 · 发布于 2024-10-02 02:30:47

您可以让函数跟踪递归调用使用的子字符串的长度:

def stringIntoList(string):
    output = []
    token = ''
    index = 0
    while index < len(string):
        char = string[index]
        index += 1
        if char in '() ' and token:
            output.append(token)
            token = ''
        if char == '(':
            lst, offset = stringIntoList(string[index:])
            output.append(lst)
            index += offset
        elif char == ')':
            break
        elif char != ' ':
            token += char
    return output, index

以便:

stringIntoList('(* (+ int (+ int real)) int)')[0][0]

退货:

['*', ['+', 'int', ['+', 'int', 'real']], 'int']

请注意,第一个[0]是为了获取列表,因为第二个项目是偏移量,而第二个[0]是为了获取列表的第一个子列表,因为您显然假设您的输入总是以括号开始和结束。你知道吗

相关问题 更多 >

    热门问题