Convert List In String Format Back To List Of Float Numbers
str = [ 3.82133931e-01 4.27354313e-02 1.94678816e-03 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
Solution 1:
It seems like you should be able to just strip off the [
and ]
:
str = str.replace('[', '').replace(']', '')
And then split the string calling float on each member of the split string:
floats = [float(x) for x in str.split()]
Notice that because python strings are immutable, things like:
str.replace('[', '')
Doesn't change str
in place. Instead, it returns a new string with the requested characters removed. Since it returns a new string, we need to give that string a name (I just chose to give it the name str
again to avoid using too many names...)
Solution 2:
How about this:
floats = [ float(x) for x in re.findall('\d+\.\d+e[+\-]\d\d', str)]
Solution 3:
You should be storing your numbers in your database as floats rather than strings.
If you're using postgres you can make use of the ArrayField
from django.contrib.postgres.fields import ArrayField
my_floats = ArrayField(models.FloatField())
If you're not, you should still store them as numbers but it may require a different relational model.
Post a Comment for "Convert List In String Format Back To List Of Float Numbers"