【问题标题】:Storing last 3 scores and deleting older scores and calculating average?存储最后 3 个分数并删除旧分数并计算平均值?
【发布时间】:2016-03-30 12:11:15
【问题描述】:

我正在制作一个程序,它可以打开并读取 csv 文件并按以下方式排序:

  • 按字母顺序排列每个学生的最高分。
  • 按最高分,从高到低。
  • 平均分,从高到低。

程序应存储每个学生的最后 3 个分数。这是我陷入困境并需要帮助的部分。当按字母顺序对文件进行排序时,程序需要查看每个学生最近的 3 个分数并选择最高的数字。目前,我的代码仅按字母顺序对文件进行排序。它确实会查看他们最近的 3 个分数并选择最高的一个。这是我需要帮助的地方。

我的代码已经按从高到低对分数进行了排序,但是它会打印出每个学生获得的所有分数,而不是打印他们最近 3 个分数中的最高分数。

Andrew 1
Andrew 2
Andrew 3
Andrew 4
Andrew 5

最后,我需要帮助计算每个学生的平均分数。我猜应该这样做的方式是,将 Andrew 的最后 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":

【问题讨论】:

  • 由于输入文件中似乎没有任何时间 pr 日期信息,程序应该如何确定最后 3 个分数是多少?另外,每个学生的分数是否在输入文件中分组在一起?
  • 不清楚你的意思是最后出现的还是最高的,但对于前者,你想要collections.dequemaxlen=3,对于后者你想要heapq.nlargest

标签: python sorting csv python-3.x average


【解决方案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 你可以使用内置函数round(),比如round(4.66724234, 1)。谷歌是你的朋友,:)
【解决方案2】:

我可以建议你看看 pandas(它是 anacondas 发行版的一部分)

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 的 DataAnalysis,其中解释了很多内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多