Python-ValueError:无法将字符串转换为浮点:[9000]

Python-ValueError:无法将字符串转换为浮点:[9000],python,Python,我试图理解这个错误消息(Python2.7)。我知道以前有人问过这个问题,但我不理解那里给出的解释,所以我再次问 这是我的密码: 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]+',

我试图理解这个错误消息(Python2.7)。我知道以前有人问过这个问题,但我不理解那里给出的解释,所以我再次问

这是我的密码:

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)
重新导入
名称=原始输入(“输入文件:”)
如果len(name)<1:name=“file.txt”
句柄=打开(名称)
y=列表()
对于线输入句柄:
line=line.rstrip()
如果关于findall(“[0-9]+”,第行)!=[] :        
y、 追加(关于findall('[0-9]+',行))
a=[y中b的映射(int,b)]
对于范围(len(a))内的x:
如果len(a[x])==1:
b=str(a[x])
c=浮动(b)

如果您更频繁地打印,您将看到发生了什么

您已经创建了一个列表列表

所以a[x]本身就是一个列表

当您将列表字符串化为“[9000]”

所以你不能用它来做一个浮点数,因为它不是一个数字

你必须剥去支架;或者不创建列表列表作为开始

使用您的帖子作为输入:

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]
它将工作并返回

9
0
0
0
0
2
7

你能提供一些以前文章的链接吗?请浏览一下,希望你能找到你的答案:看起来你试图将字符串“[9000]”转换成一个浮点数,但这不起作用,因为它有那些额外的括号。您可以在正在阅读的文件中修复此问题,也可以通过将括号拼接出来删除括号:
“[9000]”[1:-1]=“9000”
。谢谢,这是有关列表的错误消息的一个很好的解释。
9
0
0
0
0
2
7