2014-01-27 60 views
0

我有這個列表的問題,我想每個數字乘以一定的數字,但目前列表中的每個數據都是一個字符串,如果我將列表變成一個整數或轉彎將該字符串轉換爲整數並將其變爲列表,我得到一個錯誤。整數列表python

def main(): 
    isbn = input("Enter you're 10 digit ISBN number: ") 
    if len(isbn) == 10 and isbn.isdigit(): 
     list_isbn = list(isbn) 
     print (list_isbn) 
     print (list_isbn[0] * 2) 
    else: 
     print("Error, 10 digit number was not inputted and/or letters were inputted.") 
     main() 


if __name__ == "__main__": 
    main() 
    input("Press enter to exit: ") 
+3

你沒有一個數組,你有一個清單; Python有很大的不同。 –

+0

啊,好的。謝謝 – Coder77

+0

你會得到什麼錯誤?你期望輸出什麼? –

回答

5

你最好把每個個性與整數:

list_isbn = [int(c) for c in isbn] 

演示:

>>> isbn = '9872037632' 
>>> [int(c) for c in isbn] 
[9, 8, 7, 2, 0, 3, 7, 6, 3, 2] 
0

@Martijn皮特斯因爲輸入讀取項目爲整數的答案將無法正常工作已經,在他的例子中,他將ISBN定義爲一個字符串。 -

問題是len內建函數是用於序列(tubles,列表,字符串)或映射(字典),isbn是int。

對於isdigit也是如此。

我已下文一個工作程序:

def main(): 
    # number to multple by 
    digit = 2 
    isbn = input("Enter you're 10 digit ISBN number: ") 
    # Liste generator that turns each the string from input into a list of ints 
    isbn = [int(c) for c in str(isbn)] 

    # this if statement checks to make sure the list has 10 items, and they are 
    # all int's 
    if len(isbn) == 10 and all(isinstance(item, int) for item in isbn): 
     # another list generator that multiples the isbn list by digit 
     multiplied = [item * digit for item in isbn] 
     print multiplied 
    else: 
     print("Error, 10 digit number was not inputted and/or letters were inputted.") 
     main() 


if __name__ == "__main__": 
    main() 
    input("Press enter to exit: ") 
0

改變這一行

isbn = input("Enter you're 10 digit ISBN number: ") 

isbn = raw_input("Enter you're 10 digit ISBN number: ")