这是我的代码,我试图使用for循环从A,B,C,D或F的用户那里获取10个学生的输入,然后打印A的总数,B的,C,D,S和F为整个班级。
student = 0
for student in range(0,10):
x = (raw_input("Enter grade here: ")).lower()
student + 1
print "Count for A's", x.count("a")
print "Count for B's", x.count("b")
print "Count for C's", x.count("c")
print "Count for D's", x.count("d")
print "Count for F's", x.count("f")
print("Done!")
目前,它只打印最终计数。我理解为什么,我只是无法弄清楚如何将它放入字典或列表中,因为我是脑力激荡。任何帮助表示赞赏。
答案 0 :(得分:0)
在python中,你不需要声明一个循环变量。您也不需要增加循环变量。 Python将负责所有这些。 而对于你的问题;你将x设置为一个字符串。不是清单。 使用此代码:
listOfGrades = [];#to clearify, declare an empty list
for student in range(10):
listOfGrades.append(raw_input("Enter grade here: ").lower());#add to the end of the list
print .... #do your stuff here
祝你好运!
答案 1 :(得分:0)
当您从零开始循环时,您不需要设置student = 0
,student
从循环中获取其值。
试试这个:
L = []
for student in range(0,10):
x = (raw_input("Enter grade here: ")).lower()
L.append(x)
d = dict((x,L.count(x)) for x in set(L))
for k,v in d.iteritems():
print "Count for {}'s : {}".format(k.capitalize(), v)