我试图编写一个程序,从一个.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')
使用dictionary comprehension:
使用
collections.Counter
对象可以轻松完成此操作:相关问题 更多 >
编程相关推荐