【问题标题】:ValueError: could not convert string to float:ValueError:无法将字符串转换为浮点数:
【发布时间】:2013-05-30 01:45:17
【问题描述】:

我对以下代码有疑问:

inputf = open('test.dat', 'r')
lines = inputf.readlines()
rico_clus_e = []
for line in lines:
    line.split()
    print line
    if (line[0] != '#'):
        rico_clus_e.append(float(line[4]))
inputf.close()

我的 test.dat 文件是:

# specn rico_all        rico_all_e  rico_clus   rico_clus_e rico_farclust   rico_far_e  extin
a119        1.07038692  0.11109547  0.61473431  0.15063627  0.32590239      0.14777812  0.207

这会在我的终端中提供以下输出:

# specn rico_all        rico_all_e  rico_clus   rico_clus_e rico_farclust   rico_far_e  extin

a119        1.07038692  0.11109547  0.61473431  0.15063627  0.32590239      0.14777812  0.207

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    rico_clus_e.append(float(line[4]))
ValueError: could not convert string to float: 

我对此感到很困惑。它与空格无关,我都检查了它们。如果您将 4 更改为 1、2 或 3,则此方法有效,因此它必须与 test.dat 文件有关,但我似乎无法弄清楚如何。我正在使用 python 2.7.3。

【问题讨论】:

  • 元素的表示(提示:repr())是...?
  • 表示为' '

标签: string python-2.7 floating-point


【解决方案1】:

line.split() 本身对line 没有任何作用。您必须存储方法调用的结果并改为使用它。

【讨论】:

  • 但为什么它适用于其他值?将 4 更改为 3、2 或 1 确实有效...对于数字 3,表示为“9”,对于元素 2,它是“1”
  • 这是因为line[3]'9',而line[2]'1'。而line[0]'a'
  • 好的,我现在明白你的回复了。它认为'9' 是内部的,但它只是指字符串。 line = line.split() 成功了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-03-23
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-04
  • 2019-12-19
相关资源
最近更新 更多