从文本文件中读取成绩数量

0 投票
2 回答
2538 浏览
提问于 2025-04-17 17:49

我正在尝试写一个程序,这个程序可以从一个.txt文件中读取成绩列表,计算每个成绩出现的次数,并告诉我有多少学生得到了这个成绩。

这个列表的格式是每行一个成绩,比如说如果有6个A,那么程序会告诉我有6个学生得到了A

我已经让代码能正常工作了,但它运行时检查的内容太多了,我觉得可以简化一下,但我不太确定怎么做。

我觉得这可能和列表或字典有关。

def distribution(filename):
    'string ==> int & string, prints out how many students got a letter grade'
    infile = open(filename,'r')
    grades = infile.read()
    aCount = grades.count('A\n')
    aMinusCount = grades.count('A-\n')
    bCount = grades.count('B\n')
    bMinusCount = grades.count('B-\n')
    cCount = grades.count('C\n')
    cMinusCount = grades.count('C-\n')
    dCount = grades.count('D\n')
    dMinusCount = grades.count('D-\n')
    fCount = grades.count('F')
    print(aCount, 'students got A')
    print(aMinusCount, 'students got A-')
    print(bCount, 'students got B')
    print(bMinusCount, 'students got B-')
    print(cCount, 'students got C')
    print(cMinusCount, 'students got C-')
    if dCount == 0:
        pass
    else:
        print(dCount, 'students got D')
    if dMinusCount == 0:
        pass
    else:
        print(dMinusCount, 'students got D-')
    print(fCount, 'students got F')

2 个回答

1

使用一种叫做“字典推导”的方法:

def distribution(filename):
    'string ==> int & string, prints out how many students got a letter grade'
    infile = open(filename,'r')
    grades = infile.read().split('\n')
    # this creates a list of the grades, without the new-line character
    infile.close()
    possible_grades = ('A', 'A-', 'B', 'B-', 'C', 'C-', 'D', 'D-', 'F')
    gradesDict = {i:grades.count(i) for i in possible_grades}
    for x in gradesDict.keys():
        print(x + ':', gradesDict[x])
3

这可以很简单地通过一个 collections.Counter 对象来实现:

import collections
infile = open(filename,'r')
grades = [g.strip() for g in infile.readlines()]
grade_counter = collections.Counter(grades)
for g, n in sorted(grade_counter.items()):
    print n, "students got", g

撰写回答