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]]
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. 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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.