2 回答

TA贡献1860条经验 获得超8个赞
您不需要安装的库,例如pandas,尽管它们确实具有易于使用的函数来计算表的平均值。
您的代码计算单个总和并计算行数,然后从中计算单个平均值。您想在同一个循环中计算所有四个平均值。通过一次性阅读整个文件,您可以更轻松地做到这一点,但我会坚持您的方法,因为这对于超大文件很重要:
with open('training2.txt') as fh:
n = 4 # number of fields we're interested in
sums = [0] * n # initialize here, outside the loop
count = 0 # and a line counter
for line in fh:
count += 1 # increment the counter
fields = line.split() # split the line outside the loop, only once
for i in range(n):
sums[i] += float(fields[i]) # add here, not in a nested loop
averages = [s / count for s in sums] # not using the name sum, as it is a built-in
print(averages)
这是假设您的代码有效并且您的文本文件实际上具有由空格分隔的值,否则您需要类似的东西 .split(',')
添加回答
举报