0

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

列表的格式是每行一个等级,因此 6A的将返回 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')
4

2 回答 2

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
于 2013-03-04T03:36:48.777 回答
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])
于 2013-03-04T03:45:21.830 回答