数据文件行中的数字平均值“+:'int'和'str'的不支持的操作数类型”

时间:2016-11-02 22:53:49

标签: python python-3.x

我正在尝试编写一些分析.csv文件的代码,然后将该文件每行的数字平均值作为列表返回。

这是我的代码,但是我得到了这个我不明白的错误!

def mean(values):
return sum(values) / len(values)


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
       means.append(mean(no_commas))
   return means

数据的示例文件是:

1,2
1,1,1,1
-1,0,1
42,17

1 个答案:

答案 0 :(得分:0)

使用csv模块可以做得更好。您可以使用csv.reader方法,该方法将文件对象作为参数,其默认分隔符为逗号:

以下是使用列表理解csv.reader对象进行此操作的一种方法:

import csv

def line_averages(filename):
    with open(filename) as f:
        reader = csv.reader(f)
        means = [sum(map(float, row))/len(row) for row in reader]
    return means

with语句在上下文中打开文件,并在我们离开该上下文后自动关闭文件。你可以包装列表comp。处理ZeroDivisionErrortry/except中应该包含文件中长度为零的行。