在python中。我需要从文本文档中计算平均值。然后,文本文档中列出的行如下所示 Bob Farnworth 11SM 1/10 我已设法按字母顺序和分数对其进行排序。 每当有人运行测试并完成测试时,它会将他们的数据存储在新行上的文本文档中,但我需要通过将每个人的分数加上并除以其中的数量来平均分数。 这是我到目前为止所得到的。
def sortdata(): #This is my menu that will allow the user to enter a number to sort the data thats been collected from the test
while True:
print("")
print("Sort menu")
print("Enter 1 to sort by Surname")
print("Enter 2 to sort by Firstname")
print("Enter 3 to sort by Form")
print("Enter 4 to sort by Score")
print("Enter 5 to sort by Average")
menu2 = input("Enter Number..")
print("")
try:
menu2 = int(menu2)
except ValueError:
print ("unacceptable")
break
if menu2 == 1:
with open('data.txt', 'r') as data:
for line in sorted(data.readlines(), key=lambda line:(line.split(' ')[1])):
print(line, end='')
if menu2 == 2:
with open('data.txt', 'r') as data:
for line in sorted(data.readlines(), key=lambda line:(line.split(' ')[0])):
print(line, end='')
if menu2 == 3:
with open('data.txt', 'r') as data:
for line in sorted(data.readlines(), key=lambda line:(line.split(' ')[2])):
print(line, end='')
if menu2 == 4:
with open('data.txt', 'r') as data:
for line in sorted(data.readlines(), key=lambda line:(line.split(' ')[3])):
print(line, end='')
def average():
if menu2 ==5:
with open('data.txt', 'r') as data:
sum = 10
for line in sorted(data.readlines(), average == sum/(line.split(' ')[3])):
print (average)
答案 0 :(得分:1)
menu2
,也许用户可能会在某个时候给出,但现在提供默认值。有些人会说你甚至应该首先编写测试,然后编写代码直到测试通过。
此外,当您询问有关无效代码的问题时,请始终提供您收到的错误消息。