[英]How to get an average from a text document in python?
In python. 在python中。 I need to calculate an average from a text document.
我需要从文本文档中计算平均值。 Then line that is set out in the text document looks like this Bob Farnworth 11SM 1 out of 10 I have managed to sort it alphabetically and by score.
然后,文本文档中列出的行看起来像这样:Bob Farnworth 11SM 1/10我设法按字母顺序和分数排序。 Each time someone runs the test and completes it, it will store their data in the text document on a new line but i need to sort their score by average by adding each persons score up and dividing it by how many there are.
每次有人运行测试并完成测试时,它将把他们的数据存储在新行中的文本文档中,但是我需要通过将每个人的得分加起来再除以多少来对他们的得分进行平均排序。 This is what i have got so far.
这就是我到目前为止所得到的。
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)
menu2
, that maybe the user will give at some point, but provide a default value for now. menu2
,也许用户会在某个时候给出,但现在提供一个默认值。 Some would say that you should even write the tests first, and code until the tests pass. 有人会说您甚至应该首先编写测试,然后编写代码直到测试通过。
Also, when you ask a question about code that does not work, always provide the error message you got. 另外,当您提出有关无法正常工作的代码的问题时,请始终提供得到的错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.