如何从平均成绩中排除计数?

时间:2018-11-21 01:58:22

标签: python count

我想弄清楚何时要显示文件时如何计数,但没有将计数加到我的平均成绩中。

def main():
    choice = "q"
    while choice != "X":
        print_menu()
        choice = input("Enter an option (D, C, X): ")
        if choice == "D":
            DisplayScores()
        elif choice == "C":
            CalcAverage()

def print_menu():
    print("D. Display Grades")
    print("C. Calculate Average")
    print("X. Exit Application")

def DisplayScores():
    try:
        infile = open("data.txt",'r')
        count = 0
        for line in infile:
            count += 1
            print(count,line.rstrip("\n"))
            line = infile.readline() 
        infile.close()
    except IOError:
        print("File does not exist.")
    except:
        print("Unknown error.")

def CalcAverage():
    Average = 0.0
    try:
        datafile = open("data.txt", 'r')
        for grade in datafile:
            total = float(grade)
            Average += total
            print("The average of the class is: ", format(Average/29, '.2f'))
    except IOError:
        print("Something is wrong with the file.")
        print("Unknown Error.")
    datafile.close()

main()

1 个答案:

答案 0 :(得分:0)

为什么每次循环都要打印平均值?在循环结束之前,您不知道平均值是多少。另外,最好将文件中的实际成绩除以29,而不是假定为29。尝试以下方法:

(df['Prediction'] & df['GroundTruth']).cumsum()
0    1
1    1
2    2
3    2
4    2
5    3

(df['Prediction'] & df['GroundTruth']).cumsum().tolist()
[1, 1, 2, 2, 2, 3]