-1

If I have a list of strings:

['   3.2 4.5 7.8 9.2 4.3 4.7 5.2',
'   3.1 4.1 1.3 8.2 4.1 3.2 3.1',
'   3.1 4.2 5.7 3.2 4.1 3.0 1.9']

How can I convert it to a list of floats so my result looks something like this:

[[3.2, 4.5, 7.8, 9.3, 4.3, 4.7, 5.2],
[3.1, 4.1, 1.3, 8.2, 4.1, 3.2, 3.1],
[3.1, 4.2, 5.7, 3.2, 4.1, 3.0, 1.9]]
Zmann3000
  • 806
  • 5
  • 13

2 Answers2

3

Use

l = ['   3.2 4.5 7.8 9.2 4.3 4.7 5.2',
'   3.1 4.1 1.3 8.2 4.1 3.2 3.1',
'   3.1 4.2 5.7 3.2 4.1 3.0 1.9']

print( [map(float, i.strip().split()) for i in l] )

Output:

[[3.2, 4.5, 7.8, 9.2, 4.3, 4.7, 5.2], [3.1, 4.1, 1.3, 8.2, 4.1, 3.2, 3.1], [3.1, 4.2, 5.7, 3.2, 4.1, 3.0, 1.9]]
  • str.split() to split element by space
  • map(float, 'YOURLIST') to apply float on all elements.
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

You can use below code:

numbers = ['   3.2 4.5 7.8 9.2 4.3 4.7 5.2',
'   3.1 4.1 1.3 8.2 4.1 3.2 3.1',
'   3.1 4.2 5.7 3.2 4.1 3.0 1.9']

print([[float(number) for number in number_list.split()] for number_list in numbers])
Rafał
  • 685
  • 6
  • 13