Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a list of lists from a string containing a NumPy value?

I have a Python script that parses inputs from the command line. One of these arguments is a string containing a list of lists (e.g. python myscript.py -b '[[0,1],[2,3],[4,5]]').
There are several ways in which I can directly convert this string into a list of lists, like json.loads() or ast.literal_eval().

It might be useful for me to be able to include NumPy values in this string, like '[[0, 2*np.pi],[-np.pi/2, np.pi/2]]' and still be able to convert this string into a list of lists. However, none of the two methods mentioned above seems to work and I couldn’t find anything suitable online.
Does anyone know a method that is able to handle this?
I’d rather not to write a method myself if something suitable already exists.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use eval():

import numpy as np
string = '[[0, 2*np.pi],[-np.pi/2, np.pi/2]]'
eval(string)

OUTPUT:
[[0, 6.283185307179586], [-1.5707963267948966, 1.5707963267948966]]

NOTE: there are some downsides when using eval, see link.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading