我需要创建一个函数来计算数据文件(.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'
不知道出了什么问题?!
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)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句