Please excuse me if I'm asking a stupid question but I believe I have an issue.
I recently started learning Python and I tried solving some Algorithm based problems. But one issue is that every Algo challenge comes with some Input file. It usually consists of some test case count, test cases etc. like
4 #cases
1 2 5 8 4 #case 1
sadjkljk kjsd #case 2
5845 45 55 4 # case 3
sad sdkje dsk # case 4
Now to start solving problem you need control on you input data. I have seen that In python developers mostly use Lists to save their input data.
I tried:
fp = open('input.txt')
for i, line in enumerate(fp.readlines()):
if i == 0:
countcase = int(i)
board.append([])
else:
if len(line[:-1]) == 0:
currentBoard += 1
board.append([])
else:
board[currentBoard].append(line[:-1])
fp.close()
But I don't feel like that's best way to parse any given input file.
What are best practices to parse the input file? Any specific tutorial or guidance I could follow?
解决方案
Don't know whether your cases are integers or strings, so I parse them as strings:
In [1]: f = open('test.txt')
In [2]: T = int(f.readline().strip())
In [3]: f.readline()
Out[3]: '\n'
In [4]: boards = []
In [5]: for i in range(T):
...: boards.append(f.readline().strip().split(' '))
...:
In [7]: for board in boards: print board
['1', '2', '5', '8', '4']
['sadjkljk', 'kjsd']
['5845', '45', '55', '4']
['sad', 'sdkje', 'dsk']
EDIT
If list comprehensions is comfortable to you, try:
boards = [f.readline().strip().split(' ') for i in range(T)]