开发者

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

开发者 https://www.devze.com 2022-12-27 03:58 出处:网络
This question already has answers here: How to convert string representation of list to a list (19 answers)
This question already has answers here: How to convert string representation of list to a list (19 answers) Closed 6 years ago.

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 l开发者_高级运维ists; 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?


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


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


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.


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号