这是我的python文件:-
TestCases-2
Input-5
Output-1,1,2,3,5
Input-7
Ouput-1,1,2,3,5,8,13我想要的是:-
test_no = 2 (No.(测试案例) testCaseInput = [5,7]testCaseOutput = [[1,1,2,3,5],[1,1,2,3,5,8,13]]列表(
我试过这样做:
testInput = testCase.readline(-10)
for i in range(0,int(testInput)):
testCaseInput = testCase.readline(-6)
testCaseOutput = testCase.readline(-7)下一步是在(',')的基础上去掉这些数字,然后将它们放入一个列表中。
奇怪的是,readline(-6)并没有给出预期的结果。
有没有更好的方法来做这件事,显然我错过了。
我不介意在这里使用序列化,但我想让某人编写一个文本文件非常简单,就像我所展示的那样,然后将数据从其中删除。怎么做?
发布于 2011-10-24 11:17:06
readline方法的负参数指定要读取的字节数。我不认为这是你想要做的。
相反,使用readline()一次将所有内容都拉到列表中更简单。
with open('data.txt') as f:
full_lines = f.readlines()
# parse full lines to get the text to right of "-"
lines = [line.partition('-')[2].rstrip() for line in full_lines]
numcases = int(lines[0])
for i in range(1, len(lines), 2):
caseinput = lines[i]
caseoutput = lines[i+1]
...这里的想法是分离关注点(数据的来源,'-‘的解析,以及如何处理这些案例的业务逻辑)。这比在每一步都有一个readline()和冗余解析逻辑要好。
发布于 2011-10-24 11:16:06
我不确定我是否按照你想做的做,但我想我会尝试这样的方法:
testCaseIn = [];
testCaseOut = [];
for line in testInput:
if (line.startsWith("Input")):
testCaseIn.append(giveMeAList(line.split("-")[1]));
elif (line.startsWith("Output")):
testCaseOut.append(giveMeAList(line.split("-")[1]));其中,giveMeAList()是一个函数,它接受一个逗号分隔的数字列表,并从中生成列表数据。
我没有测试这段代码,但当我过去想要创建配置文件时,我编写了使用这种结构的东西。
发布于 2011-10-24 11:16:22
输出-1,1,2,3,5,8,13/应该是“输出”而不是“输出”--
testCase = open('in.txt','r') testInput = int(testCase.readline().replace("TestCases-","")) for i in range(0,int(testInput)):testCaseInput =testCase.readline().replace(“输入-”,“) testCaseOutput = testCase.readline().replace("Output-",”).split(“,")
https://stackoverflow.com/questions/7874643
复制相似问题