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!
'int(“4 \ n”)'完全没问题。你不需要用''''替换'\ n'。 – zondo
谢谢@zondo,我不知道这个......它工作得很好。我还会修正问题中的代码。但不幸的是,我仍然有同样的错误。 – Thomas
你真的在文件每行的末尾有空格吗?如果你这样做,删除它们。顺便说一句,你可以使用'.split()'而不是'.split(“”)'。如果问题在于每一行末尾的空格,那也可以解决它。 – zondo