如何从保存为文本文件的文件中获取平均值

2024-09-29 23:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须从文本文件中获取以下信息:

Dom : 9
Eathan : 0
Harry : 8
Jack : 7
Jake : 0
James : 1
Jeffin : 1
Louis : 8
Sam : 0
Tom : 3
William : 0

我需要从这个文本文件中获取分数,将它们保存为int(因为它们是字符串),然后计算出平均值并打印出来。你知道吗

import random
import operator

def randomCalc():
    ops = {'+':operator.add,
           '-':operator.sub,
           '*':operator.mul,
           '/':operator.truediv}
    num1 = random.randint(0,12)
    num2 = random.randint(1,10)   
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?\n'.format(num1, op, num2))
    return answer

def askQuestion():
    answer = randomCalc()
    while True:
      try:
         guess = float(input())#The Answer the user inputs to the question asked
      except ValueError: #When anything but a interger is inputted.
        print ("That is not a valid answer")
        continue #Dosen't print Invalid Code Error
      else:
        break
    return guess == answer

def quiz():
    print('Welcome. This is a 10 question math quiz\n')
    score = 0
    for i in range(10):
        correct = askQuestion()
        if correct:
            score += 1
            print('Correct!\n')
        else:
            print('Incorrect!\n')
    print ("\nYour score was {}/10 Well done".format(score))
    print ("\nWhat is your name")
    name = str(input())
    class_name = input("\nWhich class do you wish to input results for? ")
    class_name = class_name + ".dat"    #adds '.txt' to the end of the file so it can be used to create a file under the name a user specifies

    file = open(class_name, "a")   #opens the file in 'append' mode so you don't delete all the information
    name = (name)
    file.write(str(name + " : " )) #writes the information to the file
    file.write(str(score))
    file.write('\n')
    file.close()
    return score

quiz()

viewscore_alpha = str(input("\nWould you like to view the score`s of players alphabeticaly: Yes or No"))
if viewscore_alpha == "yes".lower():
    class_name = input("\nWhich class do you wish to View results for? ")
    class_name = class_name + ".dat"
    with open(class_name) as file: #  use with to open files as it closes them automatically
        file.seek(0) # go back to start  of file
        for line in f: # print each name
            print(line)
        file.seek(0) # go back to start again
        lines = sorted(file.readlines()) # sort the names
        with open(class_name, "w") as file_save:  # write names in sorted order
            for line in lines: 
                file_save.write(line)
        file.close()
        file_save.close90
elif viewscore_average == "no".lower() :
    viewscore_average = str(input("\nWould you like to view the score`s of classes avrages?: Yes or No"))
    if viewscore_average == "yes".lower():
        chars = set("0123456789")


    else:
        viewscore_higest = str(input("\nWould you like to view the score`s of players alphabeticaly: Yes or No"))
        if viewscore_higest == "yes".lower():

这就是我的全部,我被困住了。你知道吗


Tags: thetoanswernameyouforinputis
1条回答
网友
1楼 · 发布于 2024-09-29 23:24:34

把它分解成合理的步骤。你知道吗

  1. 打开文件(初始化几个变量,我们稍后将使用)

    running_total = 0
    num_scores = 0
    with open("path/to/file.txt") as scoresfile:
    
  2. 读每一行

        for line in scoresfile:
    
  3. 把结肠上的每一行分开

            splitline = line.split(":")
    
  4. 把分数转换成整数

            score = int(splitline[1])  # splitline[1] is the score
    
  5. 把分数加到总成绩上

            running_total += score
    
  6. 增加我们读到的行数,除以平均数

            num_scores += 1
    
  7. for循环结束,然后计算平均值

    average = running_total / num_scores
    

通过列表理解的魔力,您可以将其中的几个步骤结合起来,得出更简洁的结果,如下所示:

with open('path/to/file.txt') as scoresfile:
    scores = [int(score) for line in scoresfile for 
              _, score in line.split(":")]
average = sum(scores)/len(scores)

相关问题 更多 >

    热门问题