Python等级分配功能,计算和打印等级发生的次数

时间:2015-11-02 05:59:02

标签: python function

我正在使用以下代码创建成绩分配函数:

def distribution(grades):
available_grades = [ 'A+','A','A-','B+','B','B-','C+','C','C-','F']     
fin = open(grades,'r')
gradesList = fin.readline().split(' ')
for c_grade in available_grades:
    if c_grade in gradesList:
        print('students got '+c_grade)

我使用的grade.txt文件包含所有成绩,我需要一种方法来计算该文本文件中成绩的次数,并打印出这样的数字:

 distribution('grades.txt')
6 students got A
2 students got A-
3 students got B+
2 students got B
2 students got B-
4 students got C
1 student got C-
2 students got F

但目前只打印这个:

students got A
students got A-
students got B+
students got B
students got B-
students got C
students got C-
students got F

我的grades.txt文件包含:

A A- C F C C B- B A A A- B B+ B+ B+ C C- B- A A A F

4 个答案:

答案 0 :(得分:2)

使用collections.Counter

def distribution(grades):
    available_grades = ['A+','A','A-','B+','B','B-','C+','C','C-','F']     
    with open(grades, 'r') as fin:
        gradeCounts = collections.Counter(fin.readline().split())
    for grade in available_grades:
        print(gradeCounts[grade], 'students got', grade)

答案 1 :(得分:1)

如果您不想使用集合,则以下内容应该有效:

def distribution(grades):
    available_grades = [ 'A+','A','A-','B+','B','B-','C+','C','C-','F']
    grade_dict = {}
    for grade in available_grades:
        grade_dict[grade] = 0

    fin = open(grades,'r')
    gradesList = fin.readline().split()
    fin.close()

    for grade in gradesList:
        grade_dict[grade] += 1

    for grade in available_grades:
        print(str(grade_dict[grade]) + ' students got ' + grade)

请注意,我已将参数移至split(),因此它将删除所有空格而不仅仅是空格。

答案 2 :(得分:0)

你可以使用python Counter类。

from collections import counter

# creates a new Counter object
c = Counter()

# your file contents
lst_grades = "A A- C F C C B- B A A A- B B+ B+ B+ C C- B- A A A F"

# turn lst_grades to a list containing the grades
lst_grades = lst_grades.split(" ")

# printing lst_grades for a better idea what lst_grades looks like now
# lst_grades
# > ['A', 'A-', 'C', 'F', 'C', 'C', 'B-', 'B', 'A', 'A', 'A-', 'B', 'B+',
#    'B+', 'B+', 'C', 'C-', 'B-', 'A', 'A', 'A', 'F']

# call the update method of the counter c
# update takes an iterable (e.g. a list)
# and counts the values inside this iterable
c.update(lst_grades)

# now our counter contains a dictionary with the counted grads
# c
# > Counter({'A': 6, 'C': 4, 'B+': 3, 'B': 2, 'F': 2,
#            'B-': 2, 'A-': 2, 'C-': 1})

# you can simply access every counted entry
# c["A"]
# > 6

答案 3 :(得分:0)

或者,熊猫解决方案:

fin = open(grades,'r')
grades_given = fin.readline().split()
fin.close()

pd.Series(grades_given).value_counts().reset_index(name='cnt').\
apply(lambda x: "{cnt} students got {grade}".format(cnt=x['cnt'],
      grade=x['index']),axis=1)

0     6 students got A
1     4 students got C
2    3 students got B+
3    2 students got A-
4    2 students got B-
5     2 students got F
6     2 students got B
7    1 students got C-