簡體   English   中英

Python,無法弄清楚如何保存循環變量

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

這是我的代碼,我嘗試使用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!")

當前,它僅打印最終計數。 我明白為什么,我腦子死了,我根本無法弄清楚如何將其放入字典或列表中。 任何幫助表示贊賞。

在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

祝好運!

當您從零開始循環時,您無需將student = 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM