Python sorted() function not working the way it should

14,917

sorted returns a new list. If you want to modify the existing list, use

sheet_list.sort(key = lambda ele : ele[1])
Share:
14,917
joseph
Author by

joseph

Updated on June 04, 2022

Comments

  • joseph
    joseph almost 2 years

    Basically I have a nested list that I am trying to sort through the 1'st index I copied the way that the python howto says how to do it but it doesn't seem to work and I don't understand why:

    code from the website:

    >>> student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
        ]
    >>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
        [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
    

    My code:

    def print_scores(self):
        try:
            #opening txt and reading data then breaking data into list separated by "-"
            f = open(appdata + "scores.txt", "r")
            fo = f.read()
            f.close()
            userlist = fo.split('\n')
            sheet_list = []
            for user in userlist:
                sheet = user.split('-')
                if len(sheet) != 2:
                    continue
                sheet_list.append(sheet)
            sorted(sheet_list, key = lambda ele : ele[1]) #HERE IS THE COPIED PART!
            if len(sheet_list) > 20: # only top 20 scores are printed
                sheet_list = sheet_list[len(sheet_list) - 21 :len(sheet_list) - 1]
           #prints scores in a nice table
            print "name          score"
            for user in sheet_list:
                try:
                    name = user[0]
                    score = user[1]
                    size = len(name)
                    for x in range(0,14):
                        if x > size - 1:
                            sys.stdout.write(" ")
                        else:
                            sys.stdout.write(name[x])
                    sys.stdout.write(score + "\n")
                except:
                    print ""
    
    
        except:
             print "no scores to be displayed!"
    

    The bug is that the resulting printed list is exactly like how it was in the txt as if the sorting function didn't do anything!

    Example:

    Data in txt file:

    Jerry-1284
    Tom-264
    Barry-205
    omgwtfbbqhaxomgsss-209
    Giraffe-1227
    

    What's printed:

    Name          Score
    Jerry         1284
    Tom           264
    Barry         205
    omgstfbbqhaxom209
    Giraffe       1227
    
  • joseph
    joseph over 12 years
    still doesn't work completely, the list now is Giraffe,Jerry,Barry,omgw, and tom. It should be Jerry, Giraffe, Tom, omg, Barry.
  • DSM
    DSM over 12 years
    @joseph: the sheet entries are strings. It's sorting "alphabetically", not by the value of the number. Try key=lambda ele: float(ele[1]), or convert them to numbers beforehand.