【问题标题】:Turning a string into a nested list将字符串转换为嵌套列表
【发布时间】:2019-04-24 10:08:32
【问题描述】:

我希望能够转动 字符串 例如:'(* (+ int (+ int real)) int)'
到嵌套的 list 中,其中括号是列表的开始/结束,看起来像这样(在这种情况下)

['*', ['+', '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 

【问题讨论】:

标签: python string list for-loop recursion


【解决方案1】:

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

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] 是获取列表的第一个子列表,因为您显然假设您的输入总是开始和结束带括号。

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    相关资源
    最近更新 更多