2016-04-02 160 views
1

正如你可以從標題看到我有我的Python程序中的錯誤的麻煩。(Python)ValueError:無效的文字爲int()與基10:''

基本上,我做在這一部分,是我採取其可以是含有txt文件是這樣的,輸入的文件:

0,2 3,0 4,5 7,8 9,6 10,5 12,8 15,20 17,21 21,10 
1,3 3,4 5,9 6,8 11,3 12,4 20,20 
0,0 6,6 12,5 19,6 

並將其轉換成一個數組的數組與轉換的各數成int。

這是函數:

A = [] 


# l = line 
# e = element 
# with the functions under here we take the input and store it as an array of arrays. 


def e_split(e): 
    temp = [] 
    for tv in e.split(","): 
     temp.append(int(tv)) 
    return temp 


def l_split(l): 
    temp = [] 
    for e in l.split(" "): 
     temp.append(e_split(e)) 
    return temp 


for l in fileinput.input(): 
    A.append(l_split(l)) 

隨着所得甲上面給出應該輸入(和它是,因爲它的工作原理)

A = [[[0, 2], [3, 0], [4, 5], [7, 8], [9, 6], [10, 5], [12, 8], [15, 20], [17, 21], [21, 10]], [[1, 3], [3, 4], [5, 9], [6, 8], [11, 3], [12, 4], [20, 20]], [[0, 0], [6, 6], [12, 5], [19, 6]]] 

發生在標題中給出的誤差時我改變我的輸入文件像這樣的另一個:

2,1 3,6 6,4 8,2 10,4 12,6 14,1 17,-2 18,1 21,1 23,3 24,-2 26,-2 27,1 
3,2 5,0 7,-3 10,-1 11,0 14,-1 15,-4 18,-4 21,-8 22,-12 24,-16 25,-18 27,-16 
2,3 5,4 7,-1 8,4 11,7 12,5 13,3 14,6 16,9 18,13 19,18 21,15 22,14 24,12 26,17 
3,10 4,14 7,11 8,10 9,7 12,6 13,2 16,6 19,3 20,7 23,2 26,1 27,0 29,2 
2,10 5,14 8,18 9,20 12,22 13,27 14,26 16,27 18,24 20,22 21,17 23,14 26,10 
2,3 5,2 8,3 9,3 11,-2 13,0 14,-5 15,-1 17,-1 20,3 21,8 23,3 25,5 
3,1 5,2 8,6 11,11 13,13 14,14 17,19 18,15 19,17 21,16 22,11 23,15 26,19 29,24 

這是tracerback:

Traceback (most recent call last): 
    File "max_growth_period.py", line 29, in <module> 
    A.append(l_split(l)) 
    File "max_growth_period.py", line 24, in l_split 
    temp.append(e_split(e)) 
    File "max_growth_period.py", line 17, in e_split 
    temp.append(int(tv.replace("\n", ""))) 
ValueError: invalid literal for int() with base 10: '' 

這是2天,我試圖找到問題,但我還沒有設法。


解決

感謝@zondo我只是設法解決這個問題。基本上,因爲在第二個輸入文件中我有一些空格,我沒有注意到每行結尾處,所以我只需要重寫l.split(" ")l.split()

感謝大家的幫助btw!

+0

'int(「4 \ n」)'完全沒問題。你不需要用''''替換'\ n'。 – zondo

+0

謝謝@zondo,我不知道這個......它工作得很好。我還會修正問題中的代碼。但不幸的是,我仍然有同樣的錯誤。 – Thomas

+0

你真的在文件每行的末尾有空格嗎?如果你這樣做,刪除它們。順便說一句,你可以使用'.split()'而不是'.split(「」)'。如果問題在於每一行末尾的空格,那也可以解決它。 – zondo

回答

1

你的問題是,你使用.split(" ")

>>> "this ".split(" ") 
['this', ''] 

由於您的線路末有空格,您正在創建包含一個空字符串列表。

>>> "this ".split() 
['this'] 

如果您將參數移除到.split(),那應該可以解決您的問題。

相關問題