ValueError:Python中float()的无效文字 [英] ValueError: invalid literal for float() in Python
问题描述
我好奇有人能帮我理解错误:ValueError:float()的无效文字。当我传递一个文本文件到一个列表,然后试图将这个列表转换为浮点值的时候,我得到了这个。
a = open(input.txt,r)
$ p $ >
lines = a.readlines()
b = map(float,lines)
奇怪的是,至少对我来说,当我处理时:
print repr(lines [0])
我得到:
<0.000> 0,000 ... \0.00000\\t0.000\\\
'
和
$ b $打印类型(行[0])
我得到:
< type'str'>
我不明白为什么map(float,lines)不能正常工作。我是否错误地使用了这个功能?看看这个文档,map函数给出如下:map(function,iterable,...)。列表不可迭代吗?
另外,如果有人能解释这个错误/指向我解释这个错误的方向,我将不胜感激。
在此先感谢您的帮助。
解决方案 你正试图在你的地图上转换float('0.000 \t0.000\t0.000\t0.000\\\
,这解释了您看到的错误。
')
您需要做更多处理(请参阅内嵌评论):
>>> x ='0.000 \t0.000\t0.000\t0.000\\\
'
#模拟a.readlines()列表
>>> lines = [x,]
>>>
#剥离换行符,并根据选项卡控制字符分隔值。
>>> lines_values = map(lambda l:l.strip().split('\t'),lines)
>>> lines_values
[['0.000','0.000','0.000','0.000']]
#对于行值列表中的每个值,将字符串转换为浮动。
>>> values_float = [map(float,v)for v in values]
>>> values_float
[[0.0,0.0,0.0,0.0]]
To all:
I have curious if someone can help me understand the error: ValueError: invalid literal for float(). I am getting this when I am passing a text file to a list then trying to convert this list to float values.
a = open("input.txt","r") lines = a.readlines() b = map(float, lines)
What is odd, at least to 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 don't understand therefore why the map(float, lines) does not work correctly. Am I using this function incorrectly? Looking at the documentation the map function is given as: map(function, iterable, ...). Is a list not iterable?
Also if someone could explain this error/point me in the direction of an explanation for this error I would greatly appreciate it.
Thanks in advance for help with this question.
解决方案
a.readlines()
is a list of strings, so you're trying to convertfloat('0.000\t0.000\t0.000\t0.000\n')
in your map, which explains the error you're seeing.You need to do a bit more processing (see the inline comments):
>>> 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]]
这篇关于ValueError:Python中float()的无效文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文