为什么,当我对13个数字的列表进行排序时,python是否仅返回最后一个数字?

时间:2017-08-24 17:32:03

标签: python-3.x sorting

我在文本文件中有一个名字,姓氏和分数列表,指的是学生及其考试成绩。当我对它们进行排序以便我可以找到中位数分数时,它只从sort()返回列表中的最后一个等级。我需要它来返回所有这些,但显然按顺序排序。以下是我的代码中的一部分:

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)

1 个答案:

答案 0 :(得分:0)

每次循环运行时清除列表。将分配移到循环外。