将嵌套列表字符串转换为列表

时间:2012-02-01 17:07:43

标签: python

我想将'[[0,0,0],[0,[0],1],2,[1,1,0]]'转换为嵌套列表。我知道eval,但要明白它是随意的。我宁愿不使用图书馆;但有一个Python代码 (因为我最终将分发代码)。

3 个答案:

答案 0 :(得分:5)

Python内置了两种安全的方法,astjson

>>> import ast
>>> ast.literal_eval('[[0,0,0],[0,[0],1],2,[1,1,0]]')
[[0, 0, 0], [0, [0], 1], 2, [1, 1, 0]]

>>> import json
>>> json.loads('[[0,0,0],[0,[0],1],2,[1,1,0]]')
[[0, 0, 0], [0, [0], 1], 2, [1, 1, 0]]

答案 1 :(得分:2)

>>> import json
>>> json.loads('[[0,0,0],[0,[0],1],2,[1,1,0]]')
[[0, 0, 0], [0, [0], 1], 2, [1, 1, 0]]

答案 2 :(得分:0)

好的,所以你似乎无法访问标准的python库来简化这一过程。所以你几乎不会写自己的。我会在一起快速递归下降解析器。

这是一个真正快速的黑客工作

class Input:
    """
    This class keep track of the current position in the text
    and provides utility functions
    """
    def __init__(self, input_text):
         self.input_text = input_text
         self.peek = input_text[0]
         self.position = 1

    def match(self, character):
        assert self.peek == character
        self.peek = self.input_text[self.position]
        self.position += 1

    def extract_int(self):
        text = ''
        while self.peek.isdigit():
              text += self.peek
              self.match(self.peek)
        return int(text)

def parse_list(input):
    """
    Parses input, extracting a list starting at the current point
    """
    result = []
    input.match('[')
    while input.peek != ']':
        result.append(parse_piece(input))
        if input.peek != ',':
            break
        input.match(',')
    input.match(']')
    return result

def parse_piece(input):
    """
    Extract a list element, either another list or an int
    """
    if input.peek.isdigit():
       return input.extract_int()
    elif input.peek == '[':
       return parse_list(input)
    else:
       assert False

未经测试。可能不会编译。但希望它可以让你知道在哪里看。