I have a list which has the following content:
data = ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]']
I want convert it into a list of integers in Python3, i.e:
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Is there an elegant and concise way to do it?
I have a list which has the following content:
data = ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]']
I want convert it into a list of integers in Python3, i.e:
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Is there an elegant and concise way to do it?
You could eval
each element of your list. however this is not safe as it allows arbitrary code execution.
data = [ '[1, 2, 3]' , '[4, 5, 6]' , '[7, 8, 9]' ]
[eval(x) for x in data]
A better approach would be to de-serialize using json decoding
import json
[json.loads(x) for x in data]
You can use ast.literal_eval
with map
as:
>>> from ast import literal_eval
>>> data = ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]']
>>> list(map(literal_eval, data))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
ast.literal_eval
is safe, unlike eval
. Refer Why is using 'eval' a bad practice? for details.
You can also use it with list comprehension as:
>>> [literal_eval(d) for d in data]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]