按学生ID排序学生列表

时间:2017-12-02 23:53:44

标签: python python-3.x

我似乎无法弄清楚如何按学生ID对学生列表进行排序。我有一个字符串列表,每个字符串都包含学生的姓名和ID。它看起来像这样:

student_list = ["John,4", "Jake,1", "Alex,10"]

我希望输出看起来像这样:

["Jake,1", "John,4", "Alex,10"]

我的代码如下所示:

def sort_students_by_id(student_list):
    for string in student_list:
        comma = string.find(",")+1
        student = [(string[comma:])]    

        for index in range(len(student)):
            minpos = index
            for pos in range(index+1, len(student)):
                if student[pos] < student[minpos]:
                    minpos = pos
                tmp = student[index]
                student[index] = student[minpos]
                student[minpos] = tmp
            return student_list

print(sort_students_by_id(student_list))

1 个答案:

答案 0 :(得分:2)

你可以这样做:

def sort_students_by_id(student_list):
    return sorted(student_list, key=lambda s: int(s.split(',')[-1]))

 # ['Jake,1', 'John,4', 'Alex,10']
 print(sort_students_by_id(student_list))