user20276952
user20276952

Reputation: 53

Change String to Float Python

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

Upvotes: 2

Views: 126

Answers (2)

Daraan
Daraan

Reputation: 3780

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]

EDIT: To up it to accept any case, differentiate between int/float for example:

    >>> from ast import literal_eval
    >>> new = [literal_eval(v) for inner in a for v in inner.split(",")]
    >>> new
    [1, 0, 1.2, 2, -1.5, 1.2, 3, -1.5, 0, 4, 0, 0, 5, 1.5, 1.2]

Upvotes: 1

Rahul K P
Rahul K P

Reputation: 16081

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]

Upvotes: 0

Related Questions