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).
-
I take it you mean you don't want to use a third-party library, right?Tim Pietzcker– Tim Pietzcker2012-02-01 17:10:07 +00:00Commented Feb 1, 2012 at 17:10
-
Where did this data come from? What kind of data could be in that list?Winston Ewert– Winston Ewert2012-02-01 17:24:13 +00:00Commented 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 upfrontplanargraph– planargraph2012-02-01 17:50:18 +00:00Commented 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?Winston Ewert– Winston Ewert2012-02-01 17:56:52 +00:00Commented 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 >>>planargraph– planargraph2012-02-01 19:04:28 +00:00Commented Feb 1, 2012 at 19:04
Add a comment
|
3 Answers
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.