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:
JavaScript
x
6
1
list=['1 2 3', '4 5 6']
2
for x in list:
3
x=float(x)
4
5
ValueError: could not convert string to float: '1 2 3'
6
Advertisement
Answer
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.
JavaScript
1
4
1
>>> data = ['1 2 3', '4 5 6']
2
>>> [[float(i) for i in row.split()] for row in data]
3
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
4