从文本fi中读取分数

2024-09-30 06:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个程序,从一个.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')

Tags: 列表stringcountfilename学生分数infilegrades
2条回答

使用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])

使用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

相关问题 更多 >

    热门问题