planargraph
planargraph

Reputation: 71

Convert Nested List string to Lists

I want to convert '[[0,0,0],[0,[0],1],2,[1,1,0]]' to a nested list. I am aware of eval, but understand that it's arbitrary. I would rather not use a library; but have a Python code (as I will eventually distribute code).

Upvotes: 0

Views: 1214

Answers (3)

Winston Ewert
Winston Ewert

Reputation: 45089

Ok, so you don't seem to have access to the standard python libraries that would make this easy. So you're pretty much stuck writing your own. I'd hack together a quick recursive descent parser.

Here's a real quick hack job

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

Not tested. Probably won't compile. But hopefully it gives you an idea for where to look.

Upvotes: 0

Josh Lee
Josh Lee

Reputation: 177875

There are two safe ways that are built into Python, ast and json:

>>> 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]]

Upvotes: 5

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

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

Upvotes: 2

Related Questions