[英]Sum of numbers python
假定包含一系列整数的文件名为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()
with open('numbers.txt', 'r') as f:
print sum([float(x) for x in f.read().splitlines()])
使用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')
由于您使用的是Python 3(大概是CPython),因此绝对最快的解决方案是:
with open('numbers.txt') as f:
total = sum(map(float, f))
在CPython中,这会将所有工作推到C层(无论文件大小,执行相同数目的字节代码)并流传输文件(因此,峰值内存使用量不会随文件大小而增加)。
在对float
进行求和时,您可能需要更高的精度,这是Python在math.fsum
提供的:
import math
with open('numbers.txt') as f:
total = math.fsum(map(float, f))
它稍微慢一点(没有意义;大约慢2%,给与取),但作为交换,它不会因为由于存储部分和而使用float
的累加求和而导致的精度损失舍入错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.