ValueError: invalid literal for float () in Python

To everyone:

I'm curious if anyone can help me understand the error: ValueError: invalid literal for float (). I get this when I pass a text file to a list, and then try to convert this list to float values.

a = open("input.txt","r")
lines = a.readlines()
b = map(float, lines)

What is strange, at least for me, is that when I process:

print repr(lines[0])

I get:

'0,000 \ t0.000 ... \ t0.000 \ t0.000 \ n'

and

print type(lines[0])

I get:

<type 'str'>

I do not understand why the map (float, lines) does not work correctly. Am I using this function incorrectly? Looking at the documentation, the map function is defined as: map (function, iterable, ...). Is the list not iterable?

Also, if someone can explain this error / point me towards explaining this error, I would really appreciate it.

Thanks in advance for your help in this matter.

+5
3

- .

:

b = [[float(v) for v in line.rstrip('\n').split('\t')] for line in a]

:

b = [float(v) for line in a for v in line.rstrip('\n').split('\t')]
+7

a.readlines() - , float('0.000\t0.000\t0.000\t0.000\n') , , .

(. ):

>>> x = '0.000\t0.000\t0.000\t0.000\n'
# To simulate a.readlines()' list
>>> lines = [x,]
>>> 

# Strip the newline, and separate the values based on the tab control character.
>>> lines_values = map(lambda l: l.strip().split('\t'), lines)
>>> lines_values
[['0.000', '0.000', '0.000', '0.000']]

# For each value in in the list of lines' values, convert from string to a float.
>>> values_float = [map(float, v) for v in values]
>>> values_float
[[0.0, 0.0, 0.0, 0.0]]
+2

ValueError \t . , .

>>> lines = ['0.000\t1.000\t2.000\n', '3.000\t4\t5.0\n']
>>> [[float(val) for val in line.strip().split('\t')] for line in lines]
[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]
+2

All Articles