2012-02-01 246 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 

未經測試。可能不會編譯。但希望它給你一個想法去看看。