0

多年来,我一直在摆弄这段代码,无法弄清楚如何让它通过 doctests。输出总是比正确答案少 1000。有没有一种简单的方法来更改此代码,以便它提供所需的输出?我的代码是:

def sum_numbers_in_file(filename):
    """
    Return the sum of the numbers in the given file (which only contains
    integers separated by whitespace).
    >>> sum_numbers_in_file("numb.txt")
    19138
    """
    f = open(filename)
    m = f.readline()
    n = sum([sum([int(x) for x in line.split()]) for line in f])
    f.close()
    return n

文件中的值为:

1000 
15000 
2000 
1138
4

3 回答 3

3

罪魁祸首是:

m = f.readline() 

当你在做的时候f.readline(),它正在失去 1000,这在列表理解中没有被考虑。因此错误。

这应该有效:

def sum_numbers_in_file(filename):
    """
    Return the sum of the numbers in the given file (which only contains
    integers separated by whitespace).
    >>> sum_numbers_in_file("numb.txt")
    19138
    """
    f = open(filename, 'r+')
    m = f.readlines()
    n = sum([sum([int(x) for x in line.split()]) for line in m])
    f.close()
    return n
于 2013-05-14T01:42:23.227 回答
1

你拉出第一行并将其存储在 m 中。然后永远不要使用它。

于 2013-05-14T01:42:39.363 回答
1

for您可以在一个生成器表达式中使用两个循环:

def sum_numbers_in_file(filename):
    """
    Return the sum of the numbers in the given file (which only contains
    integers separated by whitespace).
    >>> sum_numbers_in_file("numb.txt")
    19138
    """
    with open(filename) as f:
        return sum(int(x)
                   for line in f
                   for x in line.split())

上面的生成器表达式等价于

    result = []
    for line in f:
        for x in line.split():
            result.append(int(x))
    return sum(result)
于 2013-05-14T01:43:43.290 回答