I have a list of strings like this:
L=['[1,2,3]','[3,4,5,6]','[9,8,7]']
I want to make a list of list elements like this:
Y=[[1,2,3],[3,4,5,6],[9,8,7]]
How can I do it in python?
I have a list of strings like this:
L=['[1,2,3]','[3,4,5,6]','[9,8,7]']
I want to make a list of list elements like this:
Y=[[1,2,3],[3,4,5,6],[9,8,7]]
How can I do it in python?
You can use ast.literal_eval
to evaluate each string as a python literal within a list comprehension
>>> from ast import literal_eval
>>> [literal_eval(i) for i in L]
[[1, 2, 3], [3, 4, 5, 6], [9, 8, 7]]
Every element of your array is a valid JSON so you could do
import json
Y = [json.loads(l) for l in L]
You could also do this manually:
>>> L=['[1,2,3]','[3,4,5,6]','[9,8,7]']
>>> [[int(x) for x in l[1:-1].split(',')] for l in L]
[[1, 2, 3], [3, 4, 5, 6], [9, 8, 7]]
Or without split()
, as suggested by @Moinuddin Quadri in the comments:
>>> [[int(x) for x in l[1:-1:2]] for l in L]
[[1, 2, 3], [3, 4, 5, 6], [9, 8, 7]]