Python Sorted() 函数无法按应有的方式工作

问题描述 投票:0回答:1

基本上我有一个嵌套列表,我正在尝试对第一个索引进行排序 我复制了 python howto 所说的操作方法,但它似乎不起作用,我不明白为什么:

网站代码:

>>> 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)]

我的代码:

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!"

错误在于,生成的打印列表与 txt 中的完全相同,就好像排序功能没有执行任何操作一样!

示例:

txt文件中的数据:

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

打印的内容:

Name          Score
Jerry         1284
Tom           264
Barry         205
omgstfbbqhaxom209
Giraffe       1227
python list lambda nested sorting
1个回答
19
投票

sorted
返回一个新列表。如果您想修改现有列表,请使用

sheet_list.sort(key=lambda ele: ele[1])
© www.soinside.com 2019 - 2024. All rights reserved.