Python错误:无法将字符串转换为浮点数。

5
我有一些Python代码,可以从文本文件中提取字符串:
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854, ....]

Python 代码:

v = string[string.index('['):].split(',')
for elem in v:
    new_list.append(float(elem))

这会导致错误:

ValueError: could not convert string to float: [2.974717463860223e-06

为什么无法将[2.974717463860223e-06转换为浮点数?


7
你看到错误信息里的 [ 了吗? - Tim Pietzcker
5个回答

16

你的“float”前面仍有[,这会阻止解析。

为什么不使用适当的模块?例如:

>>> a = "[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> import json
>>> b = json.loads(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
或者
>>> import ast
>>> b = ast.literal_eval(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]

6
eval 是不安全的,因为它会评估任意代码。 literal_eval 只会评估某些数据结构的代码,例如列表、字典、布尔值和 None - Aaron Dufour

5
你可以按照以下方法将从文件中读取的字符串转换为浮点数列表。
>>> instr="[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> [float(e) for e in instr.strip("[] \n").split(",")]
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]

你的代码失败的原因是,你没有从字符串中去掉 '['。

3
如果没有json.loadsast.literal_eval,这将是完成任务的最佳方法。 - Steven Rumbalski

3

您正在捕获第一个括号,将 string.index("[") 更改为 string.index("[") + 1


1
这将为您提供一个浮点数列表,无需额外导入等。
s = '[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]'
s = s[1:-1]
float_list = [float(n) for n in s.split(',')]


[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]

0
v = string[string.index('[') + 1:].split(',')

index() 返回给定字符的索引,以便 '[' 包含在由 [:] 返回的序列中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接