8

如果我问的是一个愚蠢的问题,请原谅我,但我相信我有问题。

我最近开始学习 Python,并尝试解决一些基于算法的问题。但是一个问题是每个算法挑战都带有一些输入文件。它通常由一些测试用例计数、测试用例等组成,例如

4 #cases

1 2 5 8 4 #case 1
sadjkljk kjsd #case 2
5845 45 55 4 # case 3
sad sdkje dsk # case 4

现在开始解决您需要控制输入数据的问题。我已经看到,在 python 中,开发人员大多使用Lists来保存他们的输入数据。

我试过了:

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()

但我不认为这是解析任何给定输入文件的最佳方式。

解析输入文件的最佳实践是什么?我可以遵循任何具体的教程或指导吗?

4

3 回答 3

9

不知道您的案例是整数还是字符串,所以我将它们解析为字符串:

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']

编辑

如果列表推导对您来说很舒服,请尝试:

boards = [f.readline().strip().split(' ') for i in range(T)]
于 2013-04-15T03:03:14.670 回答
2

使用固定分隔符(如空格),您还可以使用:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import csv

with open("input.txt") as file: 
    reader = csv.reader(file, delimiter=' ')
    for row in reader:
        print row
于 2013-04-15T04:01:05.367 回答
1

尽管在 Python 中你总是会发现各种巧妙的技巧和节省时间的方法(事实上,真正推荐用于实际项目的一种节省时间的方法是with语句),但我建议在你真正熟悉文件 I/O 之前,您应该坚持以下内容:

infile = open("input.txt", "r") # the "r" is not mandatory, but it tells Python you're going to be reading from the file and not writing

numCases = int(infile.readline())
infile.readline() #you had that blank line that doesn't seem to do anything
for caseNum in range(numCases):
    # I'm not sure what the lines in the file mean, but assuming each line is a separate case and is a bunch of space-separated strings:
    data = infile.readline().split(" ")
    # You can also use data = list(map(int, infile.readline.split(" "))) if you're reading a bunch of ints, or replace int with float for a sequence of floats, etc.
    # do your fancy algorithm or calculations on this line in the rest of this for loop's body

infile.close() # in the case of just reading a file, not mandatory but frees memory and is good practice

也可以选择这样做(如果您不阅读大量数据,则完全取决于您自己的喜好):

infile = open("input.txt", "r")
lines = infile.read().strip().split("\n") # the .strip() eliminates blank lines at beginning or end of file, but watch out if a line is supposed to begin or end with whitespace like a tab or space
# There was the (now-redundant) line telling you how many cases there were, and the blank following it
lines = lines[2:]
for line in lines:
    # do your stuff here
infile.close()
于 2013-04-15T03:14:49.337 回答