我试图从文本文件中取出数字的平均值并打印出来。我已经得到了打印数字。我迷失了如何将值分配给变量并获得平均值。数字必须在文本文件中格式化为这样:
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200
def main():
numbersFile = open ('numbers.dat', 'r')
for number in numbersFile:
print number
main()
预期结果是:
"The average is 105"
非常感谢任何帮助。我试图遵循发布指南,但我是新的,所以纠正我所犯的任何错误。感谢您提前提供任何帮助!
答案 0 :(得分:0)
您需要解析数字,int(number)
会这样做(如果您的输入文件每行包含一个数字) - 然后您将数字添加到列表中(在for
之前定义为{ {1}}所以你不要一直重新初始化它以清空for中的列表。用allNumbers = []
将解析后的数字附加到它。
在for循环之外,您将返回列表中的数字:
平均功能将计算平均值(另请参阅:Finding the average of a list)
allNumbers.append(mynumber)
我的avg-computing使用内置def avg(myl):
return (sum(myl)+0.0) / len(myl) # + 0.0 needed in 2.x to make it a float
def readNumbersFromFile( filename ):
'''Function that takes a filepath and parses it. The file is required to
consist out of integer numbers only - text or floating point numbers
are not handled and lead to exceptions. The file format allows for
multiple integer numbers seperated by spaces per line and for multiple
lines and will parse all numbers into one flat list and return it.'''
numbersFile = open (filename, 'r') # open file for read
allNumbers = [] # result list
for line in numbersFile: # reads one line
for number in line.split(" "): # splits one line into single numbers
allNumbers.append(int(number)) # adds each number as integer to list
return allNumbers # returns the list from this function
nums = readNumbersFromFile(r'numbers.dat')
print("The average is ", avg(nums))
- 您还可以通过添加列表中的所有元素并除以列表中的项目数来自行计算平均值
答案 1 :(得分:0)
这有效:
S = open("numbers.dat").read()
from statistics import mean
print(mean(map(int,S.split())))
它如何运作: