2017-03-19 177 views
-1

我想了解此错误消息(Python 2.7)。我发现以前有人问过这个问题,但我不明白给出的解释,所以我再次问。Python - ValueError:无法将字符串转换为浮点数:[9000]

这里是我的代码:

import re 
name = raw_input("Enter file:") 
if len(name) < 1 : name = "file.txt" 
handle = open(name) 
y = list() 
for line in handle: 
    line = line.rstrip() 
    if re.findall('[0-9]+', line) != [] :   
     y.append(re.findall('[0-9]+', line)) 
a = [map(int, b) for b in y] 
for x in range(len(a)): 
    if len(a[x]) == 1: 
     b=str(a[x]) 
     c=float(b) 
+0

你能提供一些链接到以前的帖子吗? – Tankobot

+0

请经过希望你能找到你的答案:http://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id – manoj

+0

它看起来像你试图转换字符串'[ 9000]“转换为浮点数,因为它具有这些额外的括号,所以不起作用。您可以在您正在阅读的文件中修复此问题,也可以通过拼接删除括号:''“[9000]”[1:-1] ==“9000”''。 – Tankobot

回答

1

你会看到发生了什么,如果你打印次数多

您已经创建名单

列表,这样一个[X]本身就是一个列表

当您将其列表化为列表时,它的'[9000]'

so yo你不能浮出水面,因为它不是一个数字

你将不得不去掉括号;或无法创建一个列表的列表使用您的文章作为输入与

开始:

import re 
handle = ''' 
Python - ValueError: could not convert string to float: [9000] 
Ask Question 
up vote 
0 
down vote 
favorite 


I am trying to understand this error message (Python 2.7). I see there are 
others who have asked this question previously, but I do not understand the 
explanations given there so I am asking again. Here is my code. Yes, I am a 
newbie trying to learn the basics so please keep that in mind when you answer. 
There's a reason I haven't been able to understand previous posts. 
''' 
y = list() 
print y 
for line in handle: 
    line = line.rstrip() 
    if re.findall('[0-9]+', line) != [] :   
     y.append(re.findall('[0-9]+', line)) 

print y 
a = [map(int, b) for b in y] 
print a 
for x in range(len(a)): 
    if len(a[x]) == 1: 
     b=str(a[x]) 
     print b 
     c=float(b) 

回报:

[] 
[['9'], ['0'], ['0'], ['0'], ['0'], ['2'], ['7']] 
[[9], [0], [0], [0], [0], [2], [7]] 
[9] 
Traceback (most recent call last): 
    File "test4.py", line 31, in <module> 
    c=float(b) 
ValueError: could not convert string to float: [9] 

我不知道你的最终目标是什么,但如果你这样做:

b=str(a[x][0]) 
print b 
c=float(b) 

它会工作,并返回

9 
0 
0 
0 
0 
2 
7 
+0

谢谢,这是关于列表清单的错误消息的一个很好的解释。 –

相关问题