从文本文件中读取成绩数

时间:2013-03-04 03:35:01

标签: python file

我正在尝试编写一个程序,该程序从.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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用dictionary comprehension

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])
相关问题