我想將'[[0,0,0],[0,[0],1],2,[1,1,0]]'
轉換爲嵌套列表。我知道eval
,但明白它是任意的。我寧願不使用圖書館;但有一個Python代碼 (因爲我最終會分發代碼)。將嵌套列表字符串轉換爲列表
0
A
回答
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
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
未經測試。可能不會編譯。但希望它給你一個想法去看看。
相關問題
- 1. 將嵌套字符串列表轉換爲嵌套字符串列表
- 2. 將單個字符串轉換爲嵌套列表陣列
- 3. netlogo將字符串轉換爲嵌套列表中的數字
- 4. 如何將數字的嵌套列表轉換爲字符串列表?
- 5. 將列表轉換爲嵌套字典
- 6. 嵌套列表將字符串轉換爲浮動
- 7. 將嵌套列表轉換爲查詢字符串格式?
- 8. 將字符串列表轉換爲字符串列表
- 9. 將字符串轉換爲字列表?
- 10. 將任意嵌套的文字列表轉換爲字符串表示
- 11. Python將元組列表轉換爲嵌套字典列表
- 12. 一個字符串轉換爲一個嵌套TCL列表
- 13. 將字符串轉換爲列表
- 14. 將列表轉換爲字符串
- 15. 將Enumerable.Range轉換爲字符串列表
- 16. 將字符串轉換爲列表
- 17. Java - 將字符串轉換爲列表
- 18. 將AppleScript列表轉換爲字符串
- 19. 將數組轉換爲嵌套列表
- 20. 將嵌套列表轉換爲矩陣
- 21. 嵌套列表 - 字符串爲浮動
- 22. 將字符串列表轉換爲日期列表Python 3.6
- 23. 如何將字符串列表轉換爲適當的列表?
- 24. 將列表(的對象)轉換爲列表(的字符串)
- 25. 將字符串列表轉換爲int列表
- 26. 將列表的Python列表轉換爲字符串
- 27. 如何將字符串列表轉換爲整數列表?
- 28. 將字符串查找列表轉換爲Python中的列表
- 29. 將列表列表轉換爲垂直字符串
- 30. 將字符串的混合列表轉換爲整數列表
我認爲你的意思是你不想使用第三方庫,對吧? – 2012-02-01 17:10:07
這些數據來自哪裏?該列表中可以包含哪些數據? – 2012-02-01 17:24:13
@tim,是的,我寧願不使用json或ast,因爲這些庫在我使用的集羣上不可用(並且它很容易讓管理員安裝這些庫);但只是Python代碼。 winston,數據可能是int,float或string。但我會知道數據類型 – planargraph 2012-02-01 17:50:18