查找所有行空间分隔文件的行方式平均值和平均值

时间:2014-11-18 07:51:35

标签: python

我有一个有很多行的文件,每行看起来如下:

10 55 19 51 2 9 96 64 60 2 45 39 99 60 34 100 33 71 49 13
77 3 32 100 68 90 44 100 10 52 96 95 36 50 96 39 81 25 26 13

每行作为由空格和每行(行具有不同长度)分隔的数字

如何找到每行的平均值?

如何找到所有行平均值的总和?

首选语言Python

5 个答案:

答案 0 :(得分:0)

下面的代码完成了上述任务:

def rowAverageSum(filename):
    import numpy as np
    FullMean = 0
    li = [map(int, x) for x in [i.strip().split() for i in open(filename).readlines()]]
    i=0
    while i<len(li):
        for k in li:
            print "Mean of row ",i+1,":",np.mean(k)
            FullMean+=np.mean(k)
            i+=1
    print "***************************"
    print "Grand Average:",FullMean
    print "***************************"

答案 1 :(得分:0)

使用两个实用函数words(以获取一行中的单词)和average(以获得整数序列的平均值),我会开始像

def words(s):
    return (w for w in s.strip().split())

def average(l):
    return sum(l) / len(l)

with open('input.txt') as f:
    averages = [average(map(int, words(line))) for line in f]
    total = sum(averages)

我喜欢total = sum(averages)部分,它非常类似于您的第二个要求(所有平均值的总和)。 : - )

我使用map(int, words(line))(将字符串列表转换为整数列表)只是因为它比[int(x) for x in words(line)]短,即使后者肯定会被认为是“更多Pythonic”。 / p>

答案 2 :(得分:0)

Python中的{p> 3 / 21。所以你想浮动结果你应该转换浮动。

float(3) / 21.5

>>> s = '''10 55 19 51 2 9 96 64 60 2 45 39 99 60 34 100 33 71 49 13
77 3 32 100 68 90 44 100 10 52 96 95 36 50 96 39 81 25 26 13'''
>>> line_averages = []
>>> for line in s.splitlines():
...     line_averages.append(sum([ float(ix) for ix in line.split()]) / len(line.split()))
... 
>>> line_averages
[45.55, 56.65]
>>> sum(line_averages) 
102.19999999999999

或者您可以使用reduce

>>> for line in s.splitlines():
...     line_averages.append(reduce(lambda x,y: int(x) + int(y), line.split()) / len(line.split()))
>>> line_averages
[45, 56]
>>> reduce(lambda x,y: int(x) + int(y), line_averages)
101

答案 3 :(得分:0)

如何在短时间内尝试这个?

avg_per_row = [];
avg_all_row = 0;
f1 = open("myfile") # Default mode is read    
for line in f1:
    temp = line.split();
    avg = sum([int(x) for x in temp])/length(temp)
    avg_per_row.append(avg);   # Average per row
avg_all_row = sum(avg_per_row)/len(avg_per_row) # Average for all averages

非常压缩,但应该适合你

答案 4 :(得分:0)

>>> f = open('yourfile')
>>> averages = [ sum(map(float,x.strip().split()))/len(x.strip().split()) for x in f ]
>>> averages
[45.55, 56.65]
>>> sum(averages)
102.19999999999999
>>> sum(averages)/len(averages)
51.099999999999994

strip删除&#39; \ n&#39;然后split将在空白上拆分将给出数字列表,地图将所有数字转换为浮点类型。总和将总和所有数字。

如果你不理解上面的代码,你可以看到这个,与上面相同但是扩展了:

>>> f = open('ll.txt')
>>> averages = []
>>> for x in f:
...     x = x.strip()   # removes newline character
...     x = x.split()   # split the lines on whitespaces and produces list of numbers
...     x = [ float(i) for i in x ]   # convert all number to type float
...     avg = sum(x)/len(x)           # calculate average ans store to variable avg
...     averages.append(avg)          # append the avg to list averages
... 
>>> averages
[45.55, 56.65]
>>> sum(averages)/len(averages)
51.099999999999994