Python:如何对文本文件中的数字求和 [英] Python: How to sum numbers from text file
问题描述
如何在python中对文本文件中的数字求和?假设我们有一些文本文档,其中包含这样的数字:
How to sum numbers from text file in python? Let's say that we have some text document that have numbers like this:
320
5203
5246
我们希望 python 打开那个文件并对这些数字求和得到结果:10769.我该怎么做?
And we want python open that file and sum those numbers to get to the result: 10769. How shall I do this?
推荐答案
如果文件不是太大,可以直接将文件读入数组,使用列表推导将行转换为整数列表,然后计算其总和:
If the file is not too big, you can just read the file into an array, use a list comprehension to convert the lines into a list of integers and then compute the sum of that:
sum([int(s.strip()) for s in open('foo.txt').readlines()])
然而,这会将整个文件读入内存.如果您的文件很大,以命令方式累积总和可能会占用较少的内存:
However, this reads the entire file into memory. If your file is large it would probably be less memory-intensive to accumulate the sum in an imperative manner:
result = 0
for s in open('foo.txt'): result += int(s.strip())
或者作为生成器表达式,这样列表就不需要存储在内存中
Or as a generator expression so that a list does not need to be stored in-memory
sum(int(s.strip()) for s in open('foo.txt'))
这篇关于Python:如何对文本文件中的数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!