简体   繁体   English

Python,无法弄清楚如何保存循环变量

[英]Python, can't figure out how to save looped variable

Here is my code, I am attempting to use a for loop to take an input from the user in terms of A, B, C, D, or F for 10 students that will then print the total number of A's, B's, C's, D's and F's for the entire class. 这是我的代码,我尝试使用for循环从用户那里获取10位学生的A,B,C,D或F的输入,然后打印出A,B,C的总数,整个班级都有D和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!")

Currently, it only prints the final count. 当前,它仅打印最终计数。 I understand why, I simply am not able to figure out how to put it into a dictionary or a list as I am braindead. 我明白为什么,我脑子死了,我根本无法弄清楚如何将其放入字典或列表中。 Any help is appreciated. 任何帮助表示赞赏。

In python you don't need to declare a looped variable. 在python中,您不需要声明循环变量。 You also don't need to increase the looped variable. 您也不需要增加循环变量。 Python will take care of all of that. Python将解决所有这些问题。 And for your question; 还有你的问题; you set x to a string. 您将x设置为字符串。 Not a list. 没有清单。 Use this code: 使用此代码:

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

Good luck! 祝好运!

You don't need to set student = 0 as you start looping from zero and student takes its value from the loop. 当您从零开始循环时,您无需将student = 0设置student = 0 ,并且student从循环中获取其值。 Try this: 尝试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM