得分高于平均水平的百分比。此功能应接受两个参数:分数列表和平均值

时间:2017-11-11 02:45:46

标签: python function

每当我运行该函数来计算高于平均值的分数百分比时,我得到输出56.301。正确答案应为34.平均值为54.8415588235294。

#This function calls on the data file
def get_meet_scores_from_file():
        input_file = open('state_meet.txt','r')
        all_around_points = []
        aline = input_file.readline()

        while aline:
            values = aline.split(',')
            all_around_points.append(float(values[2]))
            aline = input_file.readline()
        input_file.close()
        return all_around_points

    #This function calculates the average.   
    def average_scores(score_list):
        average_of_scores = 0
        list_length = len(score_list)
        for index in range (list_length):
            list_item = score_list[index]
            average_of_scores = average_of_scores + (list_item / list_length)
        return average_of_scores

    # This is the function that is causing the problem.
    #I am trying to get the code to count the number of scores above the average [enter link description here][1]so I can continue and with the code to determine the percentage.
    def percentage_above_average(score_list,average):
        above_average = score_list[0]
        for i in range(int(above_average)):
            if above_average > average:
                above_average = above_average + 1
            return above_average

2 个答案:

答案 0 :(得分:0)

percentage_above_average中的逻辑毫无意义。您所做的只是在score_list中获得第一个分数,如果它高于平均分数则添加1并返回该数字。这只会给你一个特定的分数,在这个例子中增加1;它不是百分比或任何数量。

您需要做的是循环score_list,计算得分高于平均值,并将该计数除以len(score_list)。代码看起来像这样:

def percentage_above_average(score_list,average):
    above_average = 0
    list_length = len(score_list)
    for index in range (list_length):
        if score_list[index] > average:
            above_average = above_average + 1
    return above_average / list_length

答案 1 :(得分:0)

高于平均分的分数百分比将是高于平均分的分数除以分数总数。

这是一个很好的小方法来计算满足某些条件的迭代中的某些东西

sum(1 for i in iterable if some_condition(i))

当然,我们可以通过获取包含它们的列表的长度来获得总分数

len(score_list)

所以我们可以把它们放在一起来实现我们的功能

def percentage_above_average(score_list,average):
    above_count = sum(1 for score in score_list if score > average)
    return above_count/len(score_list)
相关问题