2017-08-24 3 views
0

私は、生徒とそのテストの得点を参照するテキストファイルの名字、姓、スコアのリストを持っています。中央値を見つけることができるように並べ替えると、リストの最後のグレードだけがsort()から返されます。私はそれらのすべてを返すためにそれが必要ですが、明らかに順番にソートされています。問題のコードの一部を次に示します。13の数字のリストを並べ替えると、最後の数字だけが返されますか?

def main(): 
    #open file in read mode 
    gradeFile = open("grades.txt","r") 
    #read the column names and assign them to line1 variable 
    line1 = gradeFile.readline() 
    #tell it to look at lines 2 to the end 
    lines = gradeFile.readlines() 
    #seperate the list of lines into seperate lines 
    for line in lines: 
     #initialize grades list as an empty list 
     gradeList = [] 
     #iterate through each line and take off the \n 
     line = line.rstrip() 
     line = line.split(",") 
     grades = line[-1] 
     try: 
      gradeList.append(float(grades)) 
     except ValueError: 
      pass 
     #print(gradeList) 
    #sort the grades 
    gradeList.sort(reverse=False) 
    print(gradeList) 
+0

すべてのループで空の配列に 'gradeList'を再設定しています。あなたは 'gradeList = []'を 'for'の外側に置く必要があります。 – litelite

+0

ああ、私はそれを撃つでしょう。ありがとう! –

答えて

0

ループが実行されるたびにリストをクリアします。ループ外に割り当てを移動します。

+0

これは本当にコメントであるべきですが、問題を解決します。私はこれまでupvotingについて矛盾したことはありません! – inspectorG4dget

関連する問題