文件中所有数字的总和

时间:2013-05-14 01:39:06

标签: python

我一直在使用这段代码摆弄多年,并且无法弄清楚如何让它通过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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您可以在一个generator expression中使用两个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)