2017-12-02 89 views
-1

我似乎无法弄清楚如何按学生ID对学生列表进行排序。我有一个字符串列表,每个字符串都包含学生的姓名和他们的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

'sorted(students,key = lambda student:int(student.split(',')[1]))) ' –

+0

https://docs.python.org/3/howto/sorting.html – wwii

回答

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