2014-01-08 49 views
1

功能我希望能夠從英里改變距離的列表來公里,其中在代碼的下方位獲得英里的列表:字符串整數蟒蛇

input_string = input("Enter a list of distances, separated by spaces").strip() 

要更改列表輸入到一個整數列表,我用:

distances = input_string.split() 
print("This is what you entered: ") 
for distance in distances: 
    print(distance) 

def str2int(word): 
    """Converts the list of string of miles into a list of integers of miles""" 
    integer = int(word) 
    if int(word): 
     return integer 
    else: 
     sys.exit("Please try again and enter a list of integers.") 


def validate_all(distances): 
    """ 
    Checks if all the inputs are integers. If not all are integers, sys.exit 
    without converting any of the distances and ask to try again. 
    """ 

    true_list = [] 

    for distance in distances: 
     if str2int(distance): 
      true_list.append(distance) 

    if len(distances) == len(true_list): 
     return True 
    else: 
     return False 

print("And now, we are going to convert the first one to kilometers:") 
miles = distances[0] 

if validate_all: 
    # now, the calculation and display 
    kms = miles_int * KMPERMILE 
    print("The first distance you entered, in kilometers:", kms) 

    for i in range(1, len(distances), 1): 
     miles_int = str2int(distances[i]) 
     kms = miles_int * KMPERMILE 
     print("The next distance you entered in kilometres:", kms) 

但是,當我嘗試檢查,如果字符串列表中的所有元素都能夠變成一個整數(與validate_all(字))和有像

12 23 apples banana 5 

我的輸入,程序崩潰說,有在

str2int(word) 
-> if int(word): 

我,而不是一個值誤差得到sys.exit

任何人都可以調試此我/得到這個適合我請?

+1

你能發佈錯誤堆棧跟蹤嗎? – Christian

回答

2
>>> t = '12 23 apples banana 5' 
>>> [int(x) for x in t.split() if x.isdecimal()] 
[12, 23, 5] 
0

你可以使用一個try-except條款:

def str2int(word): 
    """Converts the list of string of miles into a list of integers of miles""" 
    try: 
     integer = int(word) 
     return integer 
    except ValueError: 
     print "here" 
     sys.exit("Please try again and enter a list of integers.") 

print(str2int("asd")) 

輸出:

here 
Please try again and enter a list of integers. 

注:

你可以閱讀更多有關在處理異常和try-except條款Python docs

0

你試圖做if int(x): ...,但int不是謂語。如果x是無法轉換爲int的字符串,則會引發ValueError。例如,如果x='0'if int(x): ...被評估爲False,儘管它是一個類似int的值。

你需要的是以下斷言:

def is_int_able(x): 
    try: 
    int(x) 
    return True 
    except ValueError: 
    return False 

有了這個,你可以這樣做:

[ int(x) for x in line.split() if is_int_able(x) ] 
0

validate_all()可以利用all()str.digit()

In [1]: all(e.isdigit() for e in ['12', '23', 'apples', 'banana', '5']) 
Out[1]: False 

In [2]: all(e.isdigit() for e in ['12', '23', '5']) 
Out[2]: True 

但是每haps更好的辦法是取消這個驗證並在列表理解中使用if過濾:

In [3]: distances = ['12', '23', 'apples', 'banana', '5'] 

In [4]: [int(km) * km_to_miles for km in distances if km.isdigit()] 
Out[4]: [7.456454304, 14.291537416, 3.10685596]