How can I convert this string to list of lists? [duplicate]

可紊 提交于 2020-01-09 07:58:42

问题


If a user types in [[0,0,0], [0,0,1], [1,1,0]] and press enter, the program should convert this string to several lists; one list holding [0][0][0], other for [0][0][1], and the last list for [1][1][0]

Does python have a good way to handle this?


回答1:


This is a little more flexible than Satoru's, and doesn't use any libraries. Still, it won't work with more deeply nested lists. For that, I think you would need a recursive function (or loop), or eval.

str = "[[0,0,0],[0,0,1],[1,1,0]]"
strs = str.replace('[','').split('],')
lists = [map(int, s.replace(']','').split(',')) for s in strs]

lists now contains the list of lists you want.




回答2:


>>> import ast
>>> ast.literal_eval('[[0,0,0], [0,0,1], [1,1,0]]')
[[0, 0, 0], [0, 0, 1], [1, 1, 0]]

For tuples

>>> ast.literal_eval('[(0,0,0), (0,0,1), (1,1,0)]')
[(0, 0, 0), (0, 0, 1), (1, 1, 0)]



回答3:


>>> import json
>>> json.loads('[[0,0,0], [0,0,1], [1,1,0]]')
[[0, 0, 0], [0, 0, 1], [1, 1, 0]]



回答4:


[[int(i) for i in x.strip(" []").split(",")] for x in s.strip('[]').split("],")]

a list comprehension in a list comprehension... but that will melt your brain




回答5:


>>> import re    
>>> list_strs = re.findall(r'\[\d+\,\d+\,\d+\]', s)
>>> [[[int(i)] for i in l[1:-1].split(',')] for l in list_str]



回答6:


>>> string='[[0,0,0], [0,0,1], [1,1,0]]'
>>> eval(string)
[[0, 0, 0], [0, 0, 1], [1, 1, 0]]
>>> a=eval(string)
>>> a
[[0, 0, 0], [0, 0, 1], [1, 1, 0]]

before passing your string to eval(), do the necessary sanitization first.



来源:https://stackoverflow.com/questions/2644221/how-can-i-convert-this-string-to-list-of-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!