如何计算多个整数列表的平均值?
我遇到了问题,试图让这个程序计算文本文件中数据的平均值。
所以这是我的代码:
import string
from operator import itemgetter
Options=("alphabetical order","highest to lowest","average score")
Option=raw_input("Which order do you want to output?" + str(Options))
choices=("Class 1","Class 2", "Class 3")
file = open("Class1.txt","r")
#Highest to Lowest
lines = file.readlines()
loopcount = len(lines)
for i in range(0,loopcount):
poszerostring = lines.pop(0)
new = str(poszerostring)
new1 = string.strip(new,'\n')
tempArray = new1.split(',')
resultsArray = [tempArray.append(poszerostring)]
name = tempArray.pop()
resultsArray.append(int(tempArray.pop()))
resultsArray.append(int(tempArray.pop()))
resultsArray.append(int(tempArray.pop()))
resultsArray.remove(None)
printedArray = resultsArray
print printedArray
if Option == "average score":
average = 0
sum = 0
for n in printedArray:
sum = sum(str(printedArray))
average = sum / 3
print average
以下是文本文件中的数据:
鲍勃,8,5,7Dylan,5,8,2
杰克,1,4,7
周杰伦,3,8,9
答案 0 :(得分:2)
您正在为大多数代码重新发明轮子。我会使用csv
包来读取文件,这使代码更清晰。 Documentation here
import csv
with open('Class1.txt') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
name = row[0] # first value on each row is a name
values = [int(value) for value in row[1:]] # make sure the other values are read as numbers (integers), not strings (text)
average = sum(values) / len(values) # note that in Python 2 this rounds down, use float(sum(values))/len(values) instead
print('{}: {}'.format(name, average))
更多指示:
Options
应该永远不要以大写字母开头;类应该; loopcount
可以替换为`for in in range(0,len(lines)); i
,只需使用for line in lines:
; sum = sum(str(printedArray))
将使用值覆盖函数sum
,使函数sum
在脚本中不再可用;始终避免使用等于现有函数名的变量名; sum(str())
因为你试图添加字符串而不是数字而赢得了工作; with open(file_name) as file_handler:
;这会打开文件并在代码块的末尾自动关闭它,从而阻止我忘记再次关闭文件(你应该总是这样做);更多关于with
here。