我需要创建一个函数来计算数据文件(.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'
不知道是什么出错了?!
请显示您的.csv文件的几行。谢谢。 – Ukimiku
1,2 \ n 1,1,1,1 \ n -1,0,1 \ n 42,17 \ n 不会让我做他们在单独的行.... –
谢谢。似乎你的问题找到了答案......关心 – Ukimiku