For the normal arrays, use ast.literal_eval
:
>>> from ast import literal_eval
>>> x = "[1,2,3,4]"
>>> literal_eval(x)
[1, 2, 3, 4]
>>> type(literal_eval(x))
<type 'list'>
>>>
numpy.array
's though are a little tricky because of how Python renders them as strings:
>>> import numpy as np
>>> x = [[1,2,3], [4,5,6]]
>>> x = np.array(x)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> x = str(x)
>>> x
'[[1 2 3]\n [4 5 6]]'
>>>
One hack you could use though for simple ones is replacing the whitespace with commas using re.sub
:
>>> import re
>>> x = re.sub("\s+", ",", x)
>>> x
'[[1,2,3],[4,5,6]]'
>>>
Then, you can use ast.literal_eval
and turn it back into a numpy.array
:
>>> x = literal_eval(x)
>>> np.array(x)
array([[1, 2, 3],
[4, 5, 6]])
>>>