2

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

2
  • 1
    You have to iterate over the strings in the list, split each string by the commas and convert each number-string to a float. If you have a specific issue while solving this yourself you can ask here with your code. Commented Oct 18, 2022 at 21:44
  • that looks like CSV, maybe you should be using the csv module, or maybe pandas to read it in Commented Oct 19, 2022 at 13:06

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

To be completely true to the OPs example, you'd need a replacement for float(v) that returns float if the string contains a decimal point and int if it doesn't.
Thanks for responding to my comment with the edit. That's a nice solution.
0

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]

2 Comments

Did you even check your results?
@MarkRansom Yeah, Just missed out , in join. Thanks for pointing that out. Updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.