2012-02-01 247 views
0

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

+0

我认为你的意思是你不想使用第三方库,对吧? – 2012-02-01 17:10:07

+0

这些数据来自哪里?该列表中可以包含哪些数据? – 2012-02-01 17:24:13

+0

@tim,是的,我宁愿不使用json或ast,因为这些库在我使用的集群上不可用(并且它很容易让管理员安装这些库);但只是Python代码。 winston,数据可能是int,float或string。但我会知道数据类型 – planargraph 2012-02-01 17:50:18

回答

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

未经测试。可能不会编译。但希望它给你一个想法去看看。