【问题标题】:Sum of numbers python数字之和python
【发布时间】:2015-12-16 18:31:00
【问题描述】:

假设包含一系列整数的文件名为 numbers.txt 并且存在于计算机磁盘上。编写一个程序,读取文件中存储的所有数字并计算它们的总数。

程序没有返回任何错误,但我得到了错误的总数。我得到 5,750,884.00,应该得到 284.00

这是我目前想出的:

def main():
    # Accumulator.
    total=0.0

    try:
        # Open the file
        infile = open('numbers.txt', 'r')
        #read the values from the file and accumulate them.
        for line in infile:
            amount = float(line)
            total+=amount

        # Close the file.
        infile.close()
    except exception as error:
        print(err)
    else:
        # Print the total.
        print(format(total,',.2f'))



main()    

【问题讨论】:

  • 啊,我错过了你给出预期输出的那一行。你给文件提供什么输入?
  • 您的代码在我看来是正确的;你怎么知道预期的输出是什么?
  • 我复制并粘贴了这段代码,创建了自己的 numbers.txt,它运行良好。
  • 我在这里看到的唯一错误不会影响你得到的总和;无用的 except 块对其捕获的异常使用两个不同的名称,并且文件以异常不安全的方式关闭。
  • 您是否得到相同的答案:sum(map(int, open('numbers.txt')))?或者,如果一行上可能有多个整数并忽略其他任何内容;你可以use this。虽然如果行不是很长并且它们只包含以空格分隔的整数,那么sum(i for line in open('numbers.txt') for i in map(int, line.split())) 也可以。

标签: python python-3.x


【解决方案1】:
with open('numbers.txt', 'r') as f:
    print sum([float(x) for x in f.read().splitlines()])

【讨论】:

  • 优雅。如果没有列表,这是否也有效,并且可能更有效?像这样:sum(float(x) for x in f.read().splitlines())
  • @Riccati:实际上,这仍然很浪费,因为它会将整个文件吞入list,使用潜在的大量内存,并延迟sum 的工作,直到文件被吞咽和拆分。更好的(基本上零内存开销)要么是sum(float(x) for x in f),要么是绝对最快的(在 Py3 中,或者在 Py2 中使用 from future_builtins import map 得到 Py3 mapsum(map(float, f))。即使不去除空格和换行符,它也可以工作,因为float 无论如何都会忽略前导和尾随空格。
  • @ShadowRanger 感谢您的解释。
  • 我的老师更喜欢我们使用本书提供的较长格式,因为他知道我们不仅仅是从谷歌获得答案。再次感谢。
【解决方案2】:

由于您使用的是 Python 3(可能是 CPython),因此绝对最快的解决方案是:

with open('numbers.txt') as f:
    total = sum(map(float, f))

在 CPython 中,这会将所有工作推送到 C 层(无论文件大小,执行相同数量的字节码),并流式传输文件(因此峰值内存使用量不会随着文件大小而增长) .

在对floats 求和时,您可能需要更高的准确度,这是 Python 通过math.fsum 提供的:

import math

with open('numbers.txt') as f:
    total = math.fsum(map(float, f))

它稍微慢一些(没有意义;可能会慢 2%,给予或接受),但作为交换,它不会遭受floats 的通用求和会因以下原因而导致的额外精度损失存储具有渐进式舍入误差的部分和。

【讨论】:

  • 我的老师更喜欢我们使用本书提供的较长格式,因为他知道我们不仅仅是从谷歌获得答案。再次感谢。我在错误的文件夹中有程序。我想我应该总是仔细检查一下。再次感谢。
  • 这不仅仅是“更高的准确度”——如果 IEEE-754 算法可用,fsum() 可能会返回一个 accurate 总和而不会损失精度。无论如何,int 应该在这里使用:“假设文件包含一系列整数。” 另外,the task is IO bound。否则,有faster waysread a file line by line than map()
【解决方案3】:

使用with 语法管理文件关闭,并使用sum 函数添加项目(使用生成器表达式)

try:
   with open('numbers.txt', 'r') as num_file:
      total = sum(float(l) for l in num_file)
   print('{:.2f}'.format(total))
except OSError as error:
   print('Error! (', error, ')')
except ValueError:
   print('File does not contain valid data')

【讨论】:

  • 仅供参考,您无需致电.strip()float(和int)构造函数已经忽略了前导和尾随空格。
  • 我的老师更喜欢我们使用本书提供的较长格式,因为他知道我们不仅仅是从谷歌那里得到答案。再次感谢。
  • 酷!我不知道。
猜你喜欢
  • 2021-10-17
  • 1970-01-01
  • 2022-07-12
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多