2017-08-24 90 views
0

我有一個名字,姓氏和分數在文本文件中引用學生和他們的測試分數。當我去排序他們以便我可以找到中間分數時,它只會從列表中最後一個分數的sort()返回。我需要它返回所有這些,但顯然按順序排序。以下是我的代碼部分:爲什麼當我排序13個數字的列表時,python是否只返回最後一個數字?

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 = []'這個行放在''外面' – litelite

+0

哦,好的,我會給你一個鏡頭。謝謝! –

回答

0

每次循環運行時清除列表。將分配移至循環外部。

+0

這真的應該是一個評論,但它確實解決了這個問題。我從來沒有對這種衝突抱怨! – inspectorG4dget

相關問題