Python ValueError: 无法将字符串转换为浮点数:'.'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45046281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:38:51  来源:igfitidea点击:

ValueError: could not convert string to float: '.'

pythonfloating-pointstring-conversionvalueerror

提问by Leo

I have a list of strings (CD_cent) like this:

我有一个像这样的字符串列表(CD_cent):

2.374 2.559 1.204

and I want to multiply these numbers with a float number. For this I try to convert the list of strings to a list of floats for example with:

我想将这些数字与浮点数相乘。为此,我尝试将字符串列表转换为浮点数列表,例如:

CD_cent2=[float(x) for x in CD_cent]

But I always get the error: ValueError: could not convert string to float: '.'. I guess this means, that it can't convert the dot to a float (?!) But how could I fix this? Why doesn't it recognize the dot?

但我总是收到错误:ValueError: could not convert string to float: '.'. 我想这意味着它无法将点转换为浮点数(?!)但是我该如何解决这个问题?为什么它不识别点?

采纳答案by pythad

You need to spliteach string as the string has multiple values:

您需要split每个字符串,因为字符串有多个值:

your_str = "2.374 2.559 1.204"

floats = [float(x) for x in your_str.split(' ')]

Having a list you can do something like this:

拥有一个列表,您可以执行以下操作:

li = [...]
floats = []

for s in li:
    floats.extend([float(x) for x in s.split(' ')])

In your exact situation you have a single string CD_cent = 2.374 2.559 1.204, so you can just:

在您的确切情况下,您只有一个 string CD_cent = 2.374 2.559 1.204,因此您可以:

floats = [float(x) for x in CD_cent.split(' ')]

回答by Ofer Sadan

When I ran your line with the provided data everything worked fine and all the strings converted to floats without error. The error indicates that somewhere in your CD_centthere is a single DOT .that really can't be converted to float.

当我使用提供的数据运行您的行时,一切正常,所有字符串都转换为浮点数而没有错误。该错误表明您的某处CD_cent有一个.确实无法转换为浮动的DOT 。

To try to solve this do:

要尝试解决此问题,请执行以下操作:

CD_cent2=[float(x) for x in CD_cent if x != '.']

And if that doesn't work because of other strings you will have to try...exceptlike this:

如果由于其他字符串而不起作用,您将不得不try...except喜欢这个:

CD_cent2 = []
for x in CD_cent:
    try:
        CD_cent2.append(float(x))
    except ValueError:
        pass

All of that is because I assume CD_centis not just a long string like '2.374 2.559 1.204'but it is a list like [2.374,2.559,1.204]. If that is not the case than you should splitthe line like this

所有这一切都是因为我认为CD_cent它不仅仅是一个长字符串,'2.374 2.559 1.204'而是一个像[2.374,2.559,1.204]. 如果情况并非如此,那么您应该split像这样

CD_cent2=[float(x) for x in CD_cent.split()]