Home > Software engineering >  How to get a list of lists from a string containing a NumPy value?
How to get a list of lists from a string containing a NumPy value?

Time:05-31

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.

CodePudding user response:

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.

  • Related