1

I'm trying to convert a list of strings to an array of callable float numbers in Python, but I encounter an error. Here is a part of my code:

list=['1 2 3', '4 5 6']
for x in list:
   x=float(x)

ValueError: could not convert string to float: '1 2 3'
1
  • First clarify what is the meaning of '1 2 3'. Is it 123 or is it three distinct numbers 1 then 2 and then 3 ? Commented Oct 1, 2020 at 18:56

1 Answer 1

2

You can use a nested list comprehension for this. The first can iterate through your strings, then for each string you can str.split and convert each element to float from there.

>>> data = ['1 2 3', '4 5 6']
>>> [[float(i) for i in row.split()] for row in data]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
Sign up to request clarification or add additional context in comments.

Comments

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.