'convert a string to list of list [duplicate]
I get this string for example:
s = '[1,0],[3,5],[5,6]'
I want to convert it to list.
If I do:
s.split("[*,*]")
then it doesn't work
I want to get this:
[[1,0],[3,5],[5,6]]
Solution 1:[1]
You might use literal_eval from ast module (part of standard library) for this task as follows
import ast
s = '[1,0],[3,5],[5,6]'
lst = list(ast.literal_eval(s))
print(lst)
output
[[1, 0], [3, 5], [5, 6]]
Note that s is literal for python's tuple so I used list for conversion into desired structure.
Solution 2:[2]
>>> import ast
>>> ast.literal_eval('[1,0],[3,5],[5,6]')
([1, 0], [3, 5], [5, 6])
literal_eval is more secure than eval in that it contains some logic to only actually evaluate valid literals.
Converting the result to a list() left as an exercise. (Hint hint.)
Solution 3:[3]
If the input format is really fixed :
out = [list(map(int, w.split(","))) for w in s[1:-1].split("],[")]
this may be faster but this may be less robust depending on input strict format than a real parsing solution like literal_eval
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daweo |
| Solution 2 | tripleee |
| Solution 3 | jmbarbier |
