Reputation: 47
My Script is reading data from another file. I require the data as float, not as string and I am searching for an elegant/pythonic way to combine float() with the last line instead of iterating over the entire list to change the data or changing it when I need it:
data = []
with open(os.path.join(path, file), "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
data.append(line.replace('[', ' ').replace(']', ' ').split())
So far this will save the data from the file in a list in a list as string.
How to combine the last line with float()?
Here is an example of the data before reading it:
[[ 563.15 1673.97 3078.41]
[ 563.15 1066.4 26617.7]
[ 563.212 778.931 59356.1]
Upvotes: 0
Views: 979
Reputation: 82765
Use map
Ex:
data.append(map(float, line.strip('[]').split()))
If python3
data.append(list(map(float, line.strip('[]').split())))
Upvotes: 3
Reputation: 441
Do you have numpy installed?
Because in that case you can do:
import numpy as np
with open(os.path.join(path, file), "r") as f:
data = np.array([line.strip('[]').split() for line in f],dtype=float)
it gives you a matrix in float format. Of course, this assumes that each line has the same number of values in it
Upvotes: 0