如何使用split()分隔和显示文本文件以计算和平均

2024-04-25 03:35:23 发布

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

我在使用split()函数时遇到了问题。我有一个名为printReport()的模块,每行包含一个名称和3个测试分数。我需要分割的数据,以便名称和分数可以显示,并有平均计算。我肯定我想做的是完全错误的。我得到一个IndexError: list index out of range.这只是我问题的开始。我仍然不知道如何做的计算和显示如下。你知道吗


Student Name Score 1 Score 2 Score 3 Total


Dave 82 91 77 250

Tom 79 22 84 185

Dick 67 22 91 180


Mon Feb 8 15:12:08 2016

有没有人能解释一下我做错了什么,以及我该怎么解决。你知道吗

    ### Subprogram detStudentData(fn, scores)

    def getStudentData(fn, scores):
        #   Writes instructions for the user to follow
        print("Enter the student names and scores following the prompts below.")
        print("To finish entering student names, enter: ZZZ.\n")

        #   Set the flag for the loop
        done = False
        #   Loop to get input from the usere
        while done != True:

            #   Creates a newFile and enables append
            newFile = open(fn, "a")
            #   Asks for a student name and assigns it to student_name
            student_name = input("Please enter the student name (ZZZ to finish): ")
            #   Compairs student_name to see if it is equal to "ZZZ"
            if student_name == "ZZZ":
                #   Sets the flag to True to exit the loop
                done = True
            #   Asks for test scores if student_name is not equal "ZZZ"
            else:
                #   Asks for test score 1 and assigns it to test_1
                test_1 = input("Enter score 1: ")
                #   Asks for test score 2 and assigns it to test_2
                test_2 = input("Enter score 2: ")
                #   Asks for test score 3 and assigns it to test_3
                test_3 = input("Enter score 3: ")
                print("\n")

                newFile.write(student_name) #  Writes student_name to newFile
                newFile.write(", ")         #  Writes "," to newFile
                newFile.write(test_1)       #  Writes test_1 to newFile
                newFile.write(", ")         #  Writes "," to newFile
                newFile.write(test_2)       #  Writes test_2e to newFile
                newFile.write(", ")         #  Writes "," to newFile
                newFile.write(test_3)       #  Writes test_3 to newFile
                newFile.write("\n")         #  Wites a return to newFile

            #   Closes newFile
            newFile.close()
    # ==============================================================================

    ### Subprogram getTextFileContents(fn)

    def getTextFileContents(fn):
        #   Opens the file and enables read
        with open(fn, "r") as ins:
            #   Splits the text file before the ","
            list = fn.split(",")

            #   Creates a loop to load the characters into a list
            for line in ins:
                #   Appends the text to list
                list.append(line)

        # Returns the value in list
        return list


    # ==============================================================================

    ### Subprogram printReport(line)

    def printReport(line):
        #   Prints the heading to show the test scores
        print("__________________________________________________________")
        print("Student Name     Score 1     Score 2     Score 3     Total")
        print("----------------------------------------------------------")

        name = []       #   Declare name a list
        test1 = []      #   Declare test1 a list
        test2 = []      #   Declare test2 a list
        test3 = []      #   Declare test a list

        with open("grades.txt", "r") as f:
            for line in f:
                name.append(line.split(",", 1)[0])
            line = name[0]
            capacity = len(name)
            index = 0
            while index != capacity:
                line = name[index]
                for nameOut in line.split():
                    print(nameOut)
                    index = index + 1

        # ================================================

        with open("grades.txt", "r") as f:
            for line in f:
                test1.append(line.split(",", -1)[1])
            line = test1[1]
            capacity = len(test1)
            index1 = 0
            while index1 != capacity:
                line = test1[index1]
                for t1Out in line.split():
                    print(t1Out)
                    index1 = index1 + 1

        # ================================================

        with open("grades.txt", "r") as f:
            for line in f:
                test2.append(line.split(",", -1)[2])
            line = test2[2]
            capacity = len(test2)
            index2 = 0
            while index2 != capacity:
                line = test2[index2]
                for t2Out in line.split():
                    print(t2Out)
                    index2 = index2 + 1

        # ================================================

        with open("grades.txt", "r") as f:
            for line in f:
                test3.append(line.split(" ", -1)[3])
            line = test3[3]
            capacity = len(test3)
            index3 = 0
            while index != capacity:
                line = test3[index3]
                for t3Out in line.split():
                    print(t3Out)
                    index3 = index3 + 1

    # ==============================================================================
    def main():


        fn = "grades.txt"               #   set the working file name
        scores = 3                      #   set the number of scores
        getStudentData(fn, scores)      #   Calls getStudentData()
        line = getTextFileContents(fn)  #   Assigns getTextFileContent() to line
        printReport(line)               #   Calls printReport()

    main()

Tags: thetonameintestforlinestudent
2条回答

有问题的部分是:

        while index != capacity:
            line = test3[index3]
            for t3Out in line.split():
                print(t3Out)
                index3 = index3 + 1

第一行应该是:

while index3 != capacity:

请注意,在Python中,手动递增索引可能不是循环遍历列表的最佳方法。更具Python的方式可能是:

for item in test3:
    for t3out in item.split():
         print(t3out)

另外,如果要坚持手动递增,则需要从for循环内部删除index = index + 1。只应在处理每行之后递增。你知道吗

        while index != capacity:
            line = test3[index3]
            for t3Out in line.split():
                print(t3Out)
            index3 = index3 + 1

检查线路

line = test1[1]
line = test2[2]
line = test3[3]

列表应该从0开始,而不是从123开始

相关问题 更多 >