Python Python, making a float of a list

AI Thread Summary
To convert a list of strings representing numbers into floats in Python, it's essential to ensure that the data structure is correct. The issue arises when appending to the list, as the current method creates a list of lists instead of a flat list. Instead of using `a.append(numbers)`, which adds a list of strings, concatenate the lists with `a = a + numbers`. This adjustment allows the `map(float, a)` function to work correctly, converting the strings to floats. Additionally, using print statements can help debug and clarify what data is being processed, ensuring that the input to the `map` function is a flat list of strings.
MaxManus
Messages
268
Reaction score
1
I have made a list of data from a file, the file contains numbers and I want to calculate with the numbers. How do I make a float of a list where a[1] is: ['0.00500006128645'], I tried to just use float, but then I got:
float() argument must be a string or a number
 
Technology news on Phys.org
map(float,a) will give you a list of floats.
 
I'm sorry. English is not my native language. I have a list of the acceleration of an object at some descrete and equally spaced points. And I am supposed to calculate the velocity by computing the integral numerically, but I can't manage to get the floats oit of the list.
 
If you do a=map(float,a) then a is now a list of floats. The first float is a[0], etc.
 
I tried, but I just got: TypeError: float() argument must be a string or a number

f = open("acc.dat", "r")a = []
for lines in f:
numbers = lines.split()
a.append(numbers)

f.close()

a = map(float,a)
 
Add a 'print a' statement before the 'map' statement to see what is actually going into the 'map'. You'll see that it's not a list of strings. It's a LIST of 'lists of strings'. You don't really want to append the list of strings 'lines.split()' to a, you want to concatenate it. Change 'a.append(numbers)' to 'a=a+numbers'. Python is VERY easy to debug. Use print statements to follow the program flow. If you don't understand exactly what a function does, play with it using the interactive interpreter.
 
Thank you.
 
Back
Top