首页 > 解决方案 > fileinput.input() 如何工作?

问题描述

上传包含数字 (5,5,10,10) 的 1.txt 时会引发错误:ValueError: invalid literal for int() with base 10: '5,5,10,10'

我的文件的确切内容是:5,5,10,10

我究竟做错了什么?

代码的下半部分用于黑客马拉松上传数据。之后为...

谢谢!!!

旧版:

import fileinput

def processLine(inputLine):
.....
return y

for line in fileinput.input("1.txt"):
    inputLine = int(line)
    print(processLine(inputLine))

新版本:

for line in fileinput.input():
    inputLine = line.rstrip("\n")
    inputLine = inputLine.rstrip("")
    inputLine = inputLine.split(' ')
    inputLine = list(map(int,inputLine))
    print(processLine(inputLine))

现在它适用于我的数据:5 5 10 10 但是当我在 hackathon 中编码时,我仍然收到一个错误:数据集编号:0 Traceback(最近一次调用最后一次):文件“./prog.py”,第 20 行,在 ValueError 中:基数为 10 的 int() 的无效文字:''

我怎么知道要纠正什么?

输入 唯一的输入行由 4 个空格分隔的整数组成:x1、y1、x2、y2。在 50% 的测试用例中:1 <= x1, y1, x2, y2 <= 10^3 在其他 50% 的测试用例中:1 <= x1, y1, x2, y2 <= 10^9。输出描述的矩形内的蜂箱数。

示例 输入 1 1 15 4 输出 0

输入 5 5 10 10 输出 12

标签: python

解决方案


在您的示例中,line是字符串'5,5,10,10' (所以问题不在于fileinput,而只是转换):

line = '5,5,10,10'
int(line)
# ValueError: invalid literal for int() with base 10: '5,5,10,10'

因此,您缺少拆分和映射:

list_of_input = line.split(',')
list_of_int = map(int, list_of_input)           # python2
list_of_int = list( map(int, list_of_input) )   # python3
# is now [5, 5, 10, 10]

推荐阅读