0

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).

5
  • I take it you mean you don't want to use a third-party library, right? Commented Feb 1, 2012 at 17:10
  • Where did this data come from? What kind of data could be in that list? Commented Feb 1, 2012 at 17:24
  • @tim, Yes, I would rather not use json or ast, as these libraries are not available on clusters I use (and its hassle to get admin to install these libraries); but just python code. winston, the data could be int, float or string. But I would know the datatype upfront Commented Feb 1, 2012 at 17:50
  • 1
    @user1183274, json and ast are built into python. Are you sure you don't have access to them? Commented Feb 1, 2012 at 17:56
  • @winston, >>> import json Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named json >>> import ast Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named ast >>> Commented Feb 1, 2012 at 19:04

3 Answers 3

5

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]]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.