存储最近的三次得分,删除较旧的得分并计算平均值?

4
我正在制作一个程序,该程序打开并读取一个csv文件,并按以下方式进行排序:
  • 按每个学生的最高分进行字母顺序排序。
  • 按最高分从高到低排序。
  • 按平均分从高到低排序。
该程序应为每个学生存储最近3次成绩。这是我遇到困难并需要帮助的部分。当以字母顺序对文件进行排序时,程序需要查看每个学生的最近3次成绩并选择最高分数。目前,我的代码仅按字母顺序对文件进行排序。它确实查看了他们最近的3个成绩并选择了最高分数。这就是我需要帮助的地方。
我的代码已经按最高分数排序,但它会打印出每个学生获得的所有分数,而不是打印出他们最近3次成绩中的最高分数。
Andrew 1
Andrew 2
Andrew 3
Andrew 4
Andrew 5

最后我需要帮助计算每个学生的平均分。我猜应该通过将安德鲁的最后3个分数(即5、4和3)相加,然后除以3来完成。

这是我的代码:

import csv, operator

selected_class = input("Pick a class file, (5, 6 or 7)? ")

print("1. Alphabetical order.")
print("2. Highest to lowest.")
print("3. Average score.")

selected_sorting = input("Pick an option 1, 2, or 3: ")

class_file = "Class " + selected_class + ".csv"
open_file = open(class_file)
csv_file = csv.reader(open_file)

if selected_sorting == "1":
    sorted_name = sorted(csv_file, key=operator.itemgetter(0))
    for i in sorted_name:
        print(i)

elif selected_sorting == "2":
    sorted_results = sorted(csv_file, key=lambda row: int(row[1]), reverse=True)
    for i in sorted_results:
        print(i)

elif selected_sorting == "3":

由于输入文件中似乎没有任何时间或日期信息,程序应该如何确定最后3个分数?此外,学生的分数在输入文件中是否按组排列? - martineau
不清楚您是指最后出现还是最高的,但对于前者,您需要使用collections.dequemaxlen=3,对于后者,您需要使用heapq.nlargest - ShadowRanger
2个回答

1
我将提供一些代码进行演示:

# -*- coding: utf-8 -*-
import csv
from collections import defaultdict
from statistics import mean

class_file = 'scores.csv'
open_file = open(class_file)
csv_file = csv.reader(open_file)


def main():
    # First, use student name to group by all scores, this will
    # generate structure like this:
    # {
    #     'Andrew': [1, 2, 3, 4, 5]),
    #     'Luck': [10, 20]),
    # }
    score_groups = defaultdict(list)
    for name, score in csv_file:
        score_groups[name].append(int(score))

    # Secondary, use the 3 latest socres only 
    l3_score_groups = [(key, value[-3:]) for key, value in score_groups.items()]

    print('1. Alphabetical order with each students highest score.')
    l3_highest_score_groups = [(key, max(values)) for key, values in l3_score_groups]
    for name, score in sorted(l3_highest_score_groups, key=lambda x: x[0]):
        print(name, score)

    print('2. By the highest score, highest to lowest.')
    l3_highest_score_groups = [(key, max(values)) for key, values in l3_score_groups]
    for name, score in sorted(l3_highest_score_groups, key=lambda x: x[1], reverse=True):
        print(name, score)

    print('3. Average score, highest to lowest.')
    l3_aver_score_groups = [(key, mean(values)) for key, values in l3_score_groups]
    for name, score in sorted(l3_aver_score_groups, key=lambda x: x[1], reverse=True):
        print(name, score)


if __name__ == '__main__':
    main()

以下是上面使用的技术: 希望这能有所帮助。

我已经将代码调整为我的版本并且它可以工作了。谢谢。我在想,你知道对于平均数来说,数字太长了。是否有一种方法可以将平均数四舍五入到小数点后一位呢?因此,得分4.66678变成4.7? - Hayama
@Hayama 你可以使用内置函数 round(),例如 round(4.66724234, 1)。Google 是你的朋友,:) - piglei

0

我可以建议您查看pandas(它是anaconda发行版的一部分)

import pandas as pd

dataframe = pd.read_csv(' your file ') 

print dataframe.columns

student1 = dataframe[dataframe['studentnamecolumn']=='Andrew']

last3 = student1.sort('examdatecolumnname').iloc[-3:]

avgscore = last3['examscorecolumn'].mean()

通过上述组合,您应该能够完成大多数任务。如果需要帮助,我建议阅读《Python数据分析》这本书,它解释了很多内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接