Home > Back-end >  Change String to Float Python
Change String to Float Python

Time:10-19

I would like to convert a list that I took out from a txt file into a float so I can make some calculous after in Python. I have the following list:

['1,0,1.2', '2,-1.5,1.2', '3,-1.5,0', '4,0,0', '5,1.5,1.2']

And I would like it to look like this:

[1,0,1.2,2,-1.5,1.2,3,-1.5,0,4,0,0,5,1.5,1.2]

All of them being float type.

Thank you in advance

CodePudding user response:

Two loops are needed here, an outer for the array and an inner loop over the spitted strings.

>>> new = [float(v) for inner in a for v in inner.split(",")]
>>> new
[1.0, 0.0, 1.2, 2.0, -1.5, 1.2, 3.0, -1.5, 0.0, 4.0, 0.0, 0.0, 5.0, 1.5, 1.2]

CodePudding user response:

You can do with map,

In [1]: l = ['1,0,1.2', '2,-1.5,1.2', '3,-1.5,0', '4,0,0', '5,1.5,1.2']

In [2]: list(map(float, ','.join(l).split(',')))
Out[2]: [1.0, 0.0, 1.2, 2.0, -1.5, 1.2, 3.0, -1.5, 0.0, 4.0, 0.0, 0.0, 5.0, 1.5, 1.2]
  • Related