问题
I have a list of strings (CD_cent) like this:
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?
回答1:
You need to split
each string as the string has multiple values:
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:
floats = [float(x) for x in CD_cent.split(' ')]
回答2:
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_cent
there is a single DOT .
that really can't be converted to float.
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...except
like this:
CD_cent2 = []
for x in CD_cent:
try:
CD_cent2.append(float(x))
except ValueError:
pass
All of that is because I assume CD_cent
is 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 split
the line like this
CD_cent2=[float(x) for x in CD_cent.split()]
来源:https://stackoverflow.com/questions/45046281/valueerror-could-not-convert-string-to-float