2016-04-14 10 views
1

私の問題は:ユーザーが文字列のリストを入力し、整数の周波数を見つける必要があるそして、リストにこれが私の試みです私は文字列のリストを入力し、整数、浮動小数点数などを出力するプログラムを作成する必要があります

str_s = "1,2.3, 4.3,str" 
s = str_s.split(",") 

int_s =[] 
float_s=[] 
other_s=[] 


for i in s: 
try: 
    int(s[i]) 
    int_s.append(s[i]) 
except ValueError: 
    pass 
    try: 
     float(s[i]) 
     float_s.append(s[i]) 
    except ValueError: 
     other_s.append(s[i]) 

に表示されます他の人はだから私は私の問題は、文字列でリストの要素を取り、その整数またはフロートが、私はこれを試してみたかどうかを確認するためにチェックしていると思いますが、プログラムをクラッシュさせます。

def load_list_of_strings(): 
""" 
user enters a list of strings as a string with ',' between and the function returns 
these strings as a list 
""" 
import ast 
string=input("""Enter your strings with a "," between each:""") 
if string=="": 
    return [] 
string=ast.literal_eval(string) 
string = [n.strip() for n in string] 

return string 
+0

どのようなエラーあなたは手に入れますか?あなたは入力フォーマットと希望の出力についてより具体的にすることができますか? – Francesco

答えて

2
str_s = "1,2.3, 4.3,str" 
s = str_s.split(",") 

int_s =[] 
float_s=[] 
other_s=[] 


for i in s: 
    try: 
     int_s.append(int(i)) 
    except ValueError: 
     try: 
      float_s.append(float(i)) 
     except ValueError: 
      other_s.append(i) 

print int_s 
print float_s 
print other_s 

問題はあなたのリストの要素にアクセスしようとしています: s [i]。 この問題は、 "1"、 "2.3"、 "4.3"、 "str"のいずれかになります。これらはすべて無効です。この例では唯一の有効なインデックスは次のとおりです。■[0] S [1] S [2] S [3]

+0

OP指定タグ 'python3'は、' print'コマンドの括弧を追加するだけです。 –

1

あなたはまた、(前の数字の後にスペースを許可する)正規表現を使用することができます

import re 
RE_FLOAT = re.compile(r"^\s*(\d+\.\d*)|(\d*\.\d+)\s*$") 
RE_INT = re.compile(r"^\s*\d+\s*$") 

str_s = "1,2.3, 4.3 ,.123,450.,str,A123,1001D".split(",") 
int_s = [] 
float_s = [] 
other_s = [] 
for i in str_s: 
    if RE_FLOAT.match(i): 
    float_s.append(i) 
    elif RE_INT.match(i): 
    int_s.append(i) 
    else: 
    other_s.append(i) 

print (int_s) 
print (float_s) 
print (other_s) 
関連する問題