【问题标题】:How to convert a Python string to a dimensional array or list [closed]如何将 Python 字符串转换为维度数组或列表 [关闭]
【发布时间】:2014-11-27 17:47:03
【问题描述】:

我有这个字符串:

'(+ (- 5 4) (- 2 1))'

我希望它把它转换成一个数组/列表,这样字符串的输出就会是这样的:

['+', ['-', 5, 4], ['-', 2, 1]]

括号将是数组内的一个新数组作为元素。这对我来说有点棘手,因为我是新手。提前致谢!

编辑:

如果我尝试

'(+ 1 (+ 2 (+ 4 5)))' 

输出应该是

['+', 1, ['+', 2, ['+', 4, 5]]]

【问题讨论】:

  • 你的代码在哪里,它到底有什么问题?
  • 是否保证数组中的每个对象都是单个字符?
  • 我现在的代码并没有我说的那么有用。
  • eval(re.sub(r"([+\-*/])",r"'\1'",'(+ (- 5 4) (- 2 1))').replace(" ",",")) 这是一个非常肮脏的单行解决方案。
  • @MihirSinghal ,是的,数组中的每个对象都是一个字符

标签: python arrays string list


【解决方案1】:
def interprettokens(tokens):
    ans = () # use a tuple at first so we don't get mutability problems.
    tokens = (tokens[0][1:],) + tokens[1:-1] + (tokens[-1][:-1],)
    while tokens != tuple():
        if tokens[0][0] != '(':
            ans += (tokens[0],)
            tokens = tokens[1:]
        else:
            if tokens[0][-1] == ')':
                ans += ([tokens[0][1:-1]],)
                tokens = tokens[1:]
            else:
                openParenCount = 1
                closeParenCount = 0
                index = 1
                while openParenCount != closeParenCount:
                    if tokens[index][0] == '(':
                        openParenCount += 1
                    if tokens[index][-1] == ')':
                        closeParenCount += 1
                    index += 1
                ans += (interprettokens(tokens[0:index]),)
                tokens = tokens[index:]
    return list(ans)


def interpret(string):
    tokens = tuple(string.split(' '))
    return interprettokens(tokens)

它有点长,但它有效。只需运行,例如,interpret('(+ (- 5 4) (- 2 1))'),它应该可以工作。

【讨论】:

    【解决方案2】:

    您可以使用re.split() 将字符串与() 分开,然后再将结果用空格(i.split())分开:

    >>> import re
    >>> new=[i.split() if re.search(r'\d',i) else i for i in [j for j in re.split(r'\(|\)',s) 
    >>> [[int(i) if i.isdigit() else i for i in j] if isinstance(j,list) else j for j in new]
    ['+ ', ['-', 5, 4], ['-', 2, 1]]
    

    演示:

    >>> re.split(r'\(|\)',s)
    ['', '+ ', '- 5 4', ' ', '- 2 1', '', '']
    
    >>>new= [i.split() if re.search(r'\d',i) else i for i in [j for j in re.split(r'\(|\)',s) if len(j.strip())]]
    ['+ ', ['-', '5', '4'], ['-', '2', '1']]
    >>> [[int(i) if i.isdigit() else i for i in j] if isinstance(j,list) else j for j in new]
    ['+ ', ['-', 5, 4], ['-', 2, 1]]
    

    i.strip()是因为拒绝选择空间!

    【讨论】:

    • 但是如果您不想运行多次怎么办?
    • 与预期输出不匹配
    • 数字不是ints 并且前导+ 在列表中
    • @GP89 ​​哎呀,谢谢提醒,我错过了,我会编辑!
    • 感谢卡斯拉的回复!在我尝试 '(+ 1 (+ 2 (+ 4 5)))' 之前效果很好,输出将是: [['+', 1], ['+', 2], ['+', 4 , 5]] 但是我想要的输出更像是这样的: ['+', 1, ['+', 2, ['+', 4, 5]]] 它相当递归。
    猜你喜欢
    • 2015-12-19
    • 2017-07-11
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多