2016-04-14 19 views
1

Sorunum şu: kullanıcı dizeleri bir liste girdisi ve tamsayıların frekanslarını bulmam gerekiyor ve bu benim girişimi listesinde görünür diğerleri iseDizelerin bir listesini girip, tamsayıların sayısını, yüzenleri ve diğerlerini döndüren bir program oluşturmam gerekiyor.

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]) 

Yani benim problem bir dize olan bir listenin elemanlarını alıp onun bir tamsayı veya şamandıra olmadığını görmek için kontrol düşünüyorum, ben denedim bu ama o programı

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

hangi hata aldın mı? Giriş formatı ve istenen çıktı hakkında daha spesifik olabilir misiniz? – Francesco

cevap

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 
çöküyor

Sorun, listelerinizin öğelerine erişmeyi denediğiniz gibi: s [i]. Bununla ilgili sorun "1", "2.3", "4.3" veya "str" ​​olabilir. Hepsi geçerli değil. Bu örnekte tek geçerli endeksleri şunlardır: s [0] s [1] s [2] s [3]

+0

OP belirtilen etiket 'python3',' print' komutlarının parantezini eklemeniz yeterlidir. –

1

Ayrıca (önce sayılar sonra boşluk sağlayan) normal ifadeleri kullanabilirsiniz

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) 
İlgili konular