Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找按行平均值和以空格分隔的文件的所有行的平均值_Python - Fatal编程技术网

Python 查找按行平均值和以空格分隔的文件的所有行的平均值

Python 查找按行平均值和以空格分隔的文件的所有行的平均值,python,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下面的代码执行上述任务: def rowAverageSum(filename): impo

我有一个文件,它有许多行,每一行如下所示:

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

下面的代码执行上述任务:

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 "***************************"
def rowAverageSum(文件名):
将numpy作为np导入
全均值=0
li=[i.strip().split()中x的映射(int,x)表示打开的i(filename.readlines()])]
i=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(平均值)
部分,它非常类似于您的第二个要求(所有平均值的总和)。:-)


我使用
map(int,words(line))
(将字符串列表转换为整数列表),原因很简单,因为它比
[int(x)for x in words(line)]
短,即使后者肯定会被认为是“更具Pythonic性的”。

3/2
在Python中是
1
。所以,若要对结果进行浮点运算,则应转换为浮点运算

float(3)/2
1.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

用一种简单的方式试试这个怎么样

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
非常压缩,但应该适合你

>>> 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
删除“\n”,然后
split
将在空格上拆分,将给出数字列表,map将所有数字转换为浮点型。sum将所有数字相加

如果您不理解上述代码,您可以看到以下内容,与上述内容相同,但已展开:

>>> 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

哇,一大群程序员在为你做作业,最好给他们一些介绍。我错过了你文章中的“迄今为止我尝试过的”部分question@Gullydwarf我不熟悉堆栈溢出。如果你看到下面。我自己给了答案:)这是别人问我的。但不是家庭作业:P@Sidnext2none希望一切都有帮助you@Hackaholic当然。每件事都有学习。在Technopolice@Technopolice,成为一个新的人是可以的,但是如果你阅读StackOverfow的介绍,你会发现这个问题在这个表格中并不完整,像这样把它放在StackOverflow上,对任何新发现它的人来说,都是一个糟糕的表现。@GullyDwarf,来吧。