2013-02-14 35 views

回答

3

file.txt的:

50 
25 
70 
18 
90 

的Python:

with open('file.txt') as f: 
    temps = [int(l.strip()) for l in f.readlines()] 

print(sum(temps)/len(temps)) # 50.6 
+0

由於每行只有一個數字,'l.strip()'是不必要的。 – martineau 2013-02-14 09:34:49

3

除了Nicolas的答案,如果你打算以後做更復雜的處理上,需要numpy,你可以做

import numpy, sys 
a = numpy.loadtxt('file.txt') 
m = a.mean() 
sys.stdout.write('mean = %f\n'%m) 
+0

出於好奇:你在這裏不使用'print'的原因是什麼?習慣? – 2013-02-14 08:00:00

+2

是的,習慣。由於Python 2.x <-> 3.x問題,我謹慎使用'print'。 – 2013-02-14 08:20:14

+0

如果你知道你不打算使用Python <2.6,你可以通過__future__ import print_function來完成,然後使用print的函數形式。 – 2013-02-14 08:24:25