2017-03-19 11 views
-1

このエラーメッセージ(Python 2.7)を理解しようとしています。以前この質問をしてきた人もいますが、私はそこにある説明を理解していないので、もう一度質問します。ここでPython - ValueError:stringをfloatに変換できませんでした:[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]' そう

よあなたはそれが数字ではないので、フロートを作ることができません。

あなたは括弧をはがす必要があります。

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] 

私はあなたの最終目標が何であるかわからないんだけど、あなたの場合または

入力としてあなたのポストを使用して開始するリストのリストを作成しませんそれは

0123を働いて返す

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

:これをしませんでした

9 
0 
0 
0 
0 
2 
7 
+0

ありがとう、これはリストのリストに関するエラーメッセージの良い説明です。 –

関連する問題