2016-11-02 60 views
0

我需要创建一个函数来计算数据文件(.csv)中每行数字的平均值,然后将其作为列表返回。数据文件中行的平均值

我已经设法得到数值加在一起的值,但我不知道如何除以每行数据的长度,然后将结果输入到要返回的列表中。

def line_averages(filename): 
    """ compute the average value for every line, and return the average 
    values in a list in the file "filename" """ 
    infile = open(filename, "r") 
    all_input = infile.read() 
    infile.close() 
    lines = all_input.split('\n')  # remove lines 
    for one_line in lines: 
     values = one_line.split(',') # remove commas 
     line_sum = 0 
     print(values) 
     for j in values: 
      line_sum = line_sum + float(j) 

更新:

这是新的代码,我有一种按照下面的建议之一:

def line_averages(filename): 
""" compute the average value for every line, and return the average 
values in a list in the file "filename" """ 
f = open(filename, "r") 
x = f.read() 
f.close() 
no_lines = x.split('\n')  # remove lines 
means = [] 
for i in no_lines: 
    no_commas = i.split(',') # remove commas 
    average = sum(no_commas)/len(no_commas) 
    means.append(average) 
return means 

我得到这个错误:

In [22]: line_averages("data.csv") 
Traceback (most recent call last): 

File "<ipython-input-29-e2e3fddb5de5>", line 1, in <module> 
line_averages("data.csv") 

File "E:/Google Drive/python_files/training4.py", line 19, in line_averages 
average = sum(no_commas)/len(no_commas) 

TypeError: unsupported operand type(s) for +: 'int' and 'str' 

不知道是什么出错了?!

+0

请显示您的.csv文件的几行。谢谢。 – Ukimiku

+0

1,2 \ n 1,1,1,1 \ n -1,0,1 \ n 42,17 \ n 不会让我做他们在单独的行.... –

+0

谢谢。似乎你的问题找到了答案......关心 – Ukimiku

回答

0
return_list = [] 
... 
    average = sum(values)/len(values) 
    return_list.append(average) 

此外,使用描述性的变量名。单字母变量可用于丢弃索引,但不适用于任何具有持久含义的变量。


尾翼警报

# If you have the statistics package, use "mean" from that, instead. 
def mean(coll): 
    return float(sum(coll))/max(len(coll), 1) 

def line_averages(filename): 
    """ compute the average value for every line, and return the average 
    values in a list in the file "filename" """ 

    return [mean([int(values) for values in line.split(',')]) for line in open(filename)] 
+0

谢谢!对不起,我只是在倾销脑子,所以在发布之前应该写出适当的变量。 –

+0

太好了。这些答案是否让你朝着正确的方向前进?如果是这样,请投票支持并接受你最喜欢的,所以StackOverflow可以正确地归档问题。 – Prune

+0

嗨我试过了,但得到了错误,如上所示在“更新:” –

0

基于您的代码,在每行元件的数量可以与len(c)找到。最简单的方法将这些添加到列表中,使用当前的代码,会前初始化一个空列表您的for循环:

means = [] 

然后append每个计算的平均到此列表:

means.append(s/len(c)) 

一般来说,有更高效的方法可以做到这一点(搜索'列表理解'),但这应该是最快的方法。