Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string representation of an array to an actual array in python [duplicate]

Hi doing some stuff over a network and wondering if there is any way of converting python array as a string back into a python array.. for example

x = "[1,2,3,4]"

converting x to

x_array = [1,2,3,4]

Bonus if it can also work for numpy multidimensional arrays!

like image 975
tuck Avatar asked Mar 13 '26 07:03

tuck


2 Answers

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]])
>>>
Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
>>> import json
>>> json.loads("[1,2,3,4]")
[1, 2, 3, 4]
>>> 
like image 30
warvariuc Avatar answered Mar 14 '26 20:03

warvariuc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!